<template>
  <ProjectInfo
    v-if="operationType === 2"
    :preview="true"
    :projectId="`${route.query.projectId}`"
    :reportType="'BBTUCBY'"
    :sign="true"
    :sketch="true"
    :sketchContent="`采样/测量地点设置示意图`"
    @sketch="tosketch"
    @preview-file="toPreviewJobSurvey"
  />
  <div class="job-survey">
    <ContentWrap>
      <!-- 顶部操作区 -->
      <div v-if="operationType === 1" class="head-container">
        <div class="leftadd">
          <el-button v-if="operationType === 1" type="primary" @click="handleAddTab">
            新增车间</el-button
          >
        </div>
        <!-- 右侧默认参数设置区 -->
        <div class="right-defaults">
          <div class="defaults-container">
            <!-- 工作天数和工作时间 -->
            <div class="default-item">

              <span class="item-label">d/w</span>
              <el-input-number
                v-model="defaultWorkDays"
                :max="7"
                :min="1"
                :precision="1"
                :step="0.5"
                size="small"
                style="width: 90px"
                @change="handleDefaultWorkDaysChange"
              />
            </div>

            <div class="default-item">
              <span class="item-label">h/d</span>
              <el-input-number
                v-model="defaultWorkHours"
                :max="24"
                :min="1"
                size="small"
                style="width: 80px"
                @change="handleDefaultWorkHoursChange"
              />
            </div>

            <!-- 班制设置 -->
            <div class="default-item">
              <span class="item-label">班制：</span>
              <el-select
                v-model="defaultShiftSystem"
                allow-create
                filterable
                size="small"
                style="width: 100px"
                @change="handleDefaultShiftSystemChange"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.SHIFT_DUTY)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </div>

            <!-- 工作时段（按钮打开弹窗） -->
            <div class="default-item">
              <span class="item-label">工作时段：</span>
              <div :title="'点击设置工作时段'" class="work-time-button" @click="openWorkTimeDialog">
                设置时段
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Tab区域 -->
      <div v-if="tabList.length > 0">
        <el-tabs
          v-model="activeTab"
          :closable="operationType === 1"
          type="card"
          @tab-remove="removeTab"
        >
          <el-tab-pane
            v-for="item in tabList"
            :key="item.id"
            :closable="tabList.length > 1 && operationType === 1"
            :name="item.id"
          >
            <template #label>
              <span v-if="item.isEditing">
                <el-input
                  ref="inputRef"
                  v-model="item.editingName"
                  size="small"
                  style="width: 120px"
                  @blur="handleSaveTabName(item)"
                  @keyup.enter="handleSaveTabName(item)"
                />
              </span>
              <span v-else class="tab-label">
                {{ item.name }}
                <div v-if="operationType === 1">
                  <el-tooltip content="修改车间名称" effect="light" placement="top">
                    <el-icon class="tab-icon" @click.stop="handleEditTab(item)">
                      <Edit />
                    </el-icon>
                  </el-tooltip>
                </div>

                <el-tooltip
                  v-if="operationType === 1"
                  content="复制车间"
                  effect="light"
                  placement="top"
                >
                  <el-icon class="tab-icon" @click.stop="handleCopyTab(item)">
                    <DocumentCopy />
                  </el-icon>
                </el-tooltip>
              </span>
            </template>

            <!-- Tab内容区域 -->
            <div class="tab-content">
              <!-- 添加新增岗位按钮 -->
              <div>
                <el-button
                  v-if="tabList.length > 0 && operationType === 1"
                  type="primary"
                  @click="handleAddPosition(activeTab)"
                >
                  新增岗位
                </el-button>
              </div>

              <!-- 循环渲染岗位块 -->
              <div
                v-for="position in item.positions"
                :key="position.id"
                class="position-block mb-4"
              >
                <!-- 岗位标题 -->
                <div class="position-header mb-4">
                  <div class="position-title-wrapper">
                    <div class="left-group">
                      <h3 class="position-title">
                        <span class="position-name">{{ position.name }}</span>
                        <span
                          v-if="getWorkshopNamesForPositionList(position.name).length > 1"
                          class="workshop-suffix"
                        >(跨车间：{{
                            getWorkshopNamesForPositionList(position.name).join('、')
                          }})</span
                        >
                      </h3>
                      <div v-if="operationType === 1">
                        <el-tooltip content="修改岗位名称" effect="light" placement="top">
                          <el-icon class="tab-icon" @click.stop="editPositionName(position)">
                            <Edit />
                          </el-icon>
                        </el-tooltip>
                      </div>
                      <el-tooltip
                        v-if="operationType === 1"
                        content="岗位管理"
                        effect="light"
                        placement="top"
                      >
                        <el-icon class="tab-icon" @click.stop="editPosition(position)">
                          <PriceTag />
                        </el-icon>
                      </el-tooltip>

                      <el-tooltip
                        v-if="operationType === 1"
                        content="复制岗位"
                        effect="light"
                        placement="top"
                      >
                        <el-icon class="tab-icon" @click.stop="copePosition(position)">
                          <DocumentCopy />
                        </el-icon>
                      </el-tooltip>

                      <el-tooltip
                        v-if="operationType === 1"
                        content="删除岗位"
                        effect="light"
                        placement="top"
                      >
                        <el-icon
                          class="tab-icon"
                          @click="handleDeletePosition(position.id, item.id)"
                        >
                          <Close />
                        </el-icon>
                      </el-tooltip>
                    </div>
                    <!-- 方案模式下：表格列显示设置 -->
                    <div v-if="operationType === 2" class="right-group">
                      <el-popover
                        :ref="(el) => setPopoverRef(el, position.id)"
                        :teleported="false"
                        :width="220"
                        placement="bottom-end"
                        trigger="click"
                      >
                        <!-- 内部的 div 阻止点击冒泡 -->
                        <div @click.stop>
                          <div class="column-settings">
                            <!-- 复选框现在可以正确地绑定到 tempColumnVisible 上 -->
                            <el-checkbox v-model="tempColumnVisible.testStandard"
                            >检测依据</el-checkbox
                            >
                            <el-checkbox v-model="tempColumnVisible.airCollector"
                            >空气收集器</el-checkbox
                            >
                            <el-checkbox v-model="tempColumnVisible.measuringEquipment"
                            >测量设备</el-checkbox
                            >
                            <el-checkbox v-model="tempColumnVisible.storageLife"
                            >保存期限</el-checkbox
                            >
                            <el-checkbox v-model="tempColumnVisible.flowRate"
                            >采样流量(L/min)</el-checkbox
                            >
                          </div>

                          <div class="popover-footer">
                            <el-button size="small" @click="cancelColumnSettings">取消</el-button>
                            <el-button size="small" type="primary" @click="confirmColumnSettings"
                            >确定</el-button
                            >
                          </div>
                        </div>
                        <template #reference>
                          <el-button text type="primary" @click="togglePopover(position.id)">
                            <el-icon class="mr-1"><Setting /></el-icon>
                            列设置
                          </el-button>
                        </template>
                      </el-popover>
                    </div>
                  </div>
                </div>

                <!-- 基础信息区域 -->
                <div class="base-info mb-4">
                  <el-row :gutter="20">
                    <el-col :span="4">
                      <div class="info-item">
                        <span class="label">作业类型</span>
                        <el-select
                          v-model="position.workMode"
                          :disabled="operationType === 2"
                          class="!w-[170px]"
                          placeholder="请选择"
                          @change="(val) => handleWorkModeChange(val, position)"
                        >
                          <el-option label="固定" value="固定" />
                          <el-option label="流动" value="流动" />
                        </el-select>
                      </div>
                    </el-col>
                    <el-col :span="4">
                      <div class="info-item">
                        <span class="label">接触类型</span>
                        <el-select
                          v-model="position.workPosition"
                          :disabled="operationType === 2"
                          class="!w-[180px]"
                          placeholder="请选择"
                          @change="(val) => handleWorkPositionChange(val, position)"
                        >
                          <el-option label="稳定" value="稳定" />
                          <el-option label="非稳定" value="非稳定" />
                        </el-select>
                      </div>
                    </el-col>
                    <el-col :span="4">
                      <div class="info-item">
                        <span class="label">数/班</span>
                        <el-input
                          v-model="position.shiftCount"
                          :disabled="operationType === 2"
                          :min="0"
                          controls-position="right"
                          size="default"
                          type="number"
                          @input="(val) => handleNumberInput(val, 'shiftCount', position)"
                        />
                      </div>
                    </el-col>
                    <el-col :span="4">
                      <div class="info-item">
                        <span class="label">班制</span>
                        <el-select
                          v-model="position.shiftSystem"
                          :disabled="operationType === 2"
                          allow-create
                          filterable
                          placeholder="请选择"
                          @change="(val) => handleShiftSystemChange(val, position)"
                        >
                          <el-option
                            v-for="dict in getStrDictOptions(DICT_TYPE.SHIFT_DUTY)"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </div>
                    </el-col>
                    <el-col :span="4">
                      <div class="info-item">
                        <span class="label">总人数</span>
                        <el-input
                          v-model="position.totalPeople"
                          :disabled="operationType === 2"
                          :min="0"
                          controls-position="right"
                          size="default"
                          type="number"
                          @input="(val) => handleNumberInput(val, 'totalPeople', position)"
                        />
                      </div>
                    </el-col>

                  </el-row>
                  <el-row :gutter="20">
                    <el-col v-if="position.workPosition === '非稳定'" :span="8">
                      <div class="info-item">
                        <span class="label">劳动者</span>
                        <el-input-tag
                          v-model="position.workerName"
                          :disabled="operationType === 2"
                          :trigger-on-focus="false"
                          class="!w-[450px]"
                          placeholder="请输入劳动者"
                          size="default"
                          @change="() => handleWorkerNameChange(position)"
                        />
                      </div>
                    </el-col>

                    <el-col :span="4">
                      <div class="info-item">
                        <span class="label">每周工作天</span>
                        <el-input
                          v-model="position.workDays"
                          :disabled="operationType === 2"
                          :min="0"
                          controls-position="right"
                          size="default"
                          type="number"
                          @change="handleWorkTimeChange(position)"
                          @input="(val) => handleNumberInput(val, 'workDays', position)"
                        />
                      </div>
                    </el-col>
                    <el-col :span="4">
                      <div class="info-item">
                        <span class="label">工作时间</span>
                        <el-input
                          v-model="position.workHours"
                          :disabled="operationType === 2"
                          :min="0"
                          :step="0.1"
                          controls-position="right"
                          size="default"
                          type="number"
                          @change="handleWorkTimeChange(position)"
                          @input="(val) => handleNumberInput(val, 'workHours', position)"
                        />
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="info-item">
                        <span class="label">工作时段</span>
                        <div
                          :title="'点击编辑岗位工作时段'"
                          class="work-time-display"
                          @click="operationType === 1 && openPositionWorkTimeDialog(position)"
                        >
                          {{ formatPositionWorkTime(position) }}
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="4">
                      <!-- 当接触类型为稳定时的预留空间 -->
                    </el-col>
                  </el-row>
                </div>

                <el-table
                  :key="`table-${position.id}`"
                  v-sticky-header="stickyHeaderOptions"
                  :data="
                    getExpandedTableData(position.tableData).filter(
                      (row) =>
                        operationType === 2 || (operationType === 1 && row.workLocation === 1)
                    )
                  "
                  :span-method="handleSpanMethod2"
                  border
                  class="tab-container"
                  style="width: 100%"
                >
                  <!-- 测量号：仅在方案模式显示，按工位合并显示 -->
                  <el-table-column
                    v-if="operationType === 2"
                    align="center"
                    label="测量号"
                    prop="measurementNo"
                    width="150"
                  >
                    <template #default="scope">
                      <span v-if="scope.row.isFirstHazard">
                        {{ getMeasurementLabelEx(item, position, scope.row) }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column :label="lableName" prop="testItem" width="250">
                    <template #default="scope">
                      <div v-if="scope.row.isFirstHazard" class="test-item-cell">
                        <div v-if="scope.row.editingTestItem">
                          <el-input
                            ref="testItemInputRef"
                            v-model="scope.row.editingTestItemValue"
                            size="small"
                            style="width: 120px"
                            @blur="() => handleSaveTestItem(scope.row)"
                            @keyup.enter="() => handleSaveTestItem(scope.row)"
                          />
                        </div>
                        <div
                          v-else
                          class="main-item"
                          @dblclick="() => handleEditTestItem(scope.row)"
                          v-html="scope.row.testItem"
                        ></div>
                        <!-- 操作按钮组 -->
                        <div class="testitem-action-btns">
                          <el-button
                            v-if="operationType === 1"
                            link
                            size="small"
                            type="primary"
                            @click="openHazardIdentification(scope.row)"
                          >危害识别
                          </el-button>
                          <el-button
                            v-if="operationType === 1"
                            link
                            size="small"
                            type="primary"
                            @click="openImportHazards(scope.row)"
                          >导入
                          </el-button>
                          <el-tooltip
                            v-if="!scope.row.editing"
                            :content="
                              getPositionWorkMode(scope.row) === '固定'
                                ? '固定岗位只有一个工位'
                                : ''
                            "
                            :disabled="getPositionWorkMode(scope.row) === '流动'"
                            effect="dark"
                            placement="top"
                          >
                            <el-button
                              v-if="operationType === 1"
                              :disabled="getPositionWorkMode(scope.row) === '固定'"
                              link
                              size="small"
                              type="primary"
                              @click="handleCopy(scope.row)"
                            >复制
                            </el-button>
                          </el-tooltip>
                          <el-button
                            link
                            size="small"
                            type="danger"
                            @click="handleDelete(scope.row)"
                          >
                            删除工位
                          </el-button>
                          <el-button
                            v-if="getPositionWorkMode(scope.row) === '固定'&&(scope.row.workLocation===1)&&( operationType === 2)&&( scope.row.contactTime >= 1)"
                            link
                            size="small"
                            type="danger"
                            @click="openPointMaintainDialog(scope.row)"
                          >布点维护
                          </el-button>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="危害名称">
                    <template #default="scope">
                      <template v-if="operationType === 1">
                        <template v-if="scope.row.hazards && scope.row.hazards.length">
                          <div class="hazard-name-cell">
                            <el-tag
                              v-for="hazard in getUniqueHazardsByName(scope.row.hazards)"
                              :key="hazard.cnName"
                              :class="`hazard-type-${hazard.type}`"
                              class="mr-2"
                              round
                              size="small"
                            >
                              {{ hazard.cnName }}
                              <span v-if="hazard.onlyReco" class="reco-badge">仅识别</span>
                            </el-tag>
                          </div>
                        </template>
                        <span v-else>-</span>
                      </template>
                      <template v-if="operationType === 2">
                        <template v-if="scope.row.hazard">
                          <el-tag
                            :class="`hazard-type-${scope.row.hazard.type}`"
                            class="mr-2"
                            round
                            size="small"
                          >
                            <div class="hazard-cell-content">
                            <span v-if="!scope.row.hazard.sampling.pointCount" style="text-decoration: line-through">
                              {{ scope.row.hazard.cnName }}
                            </span>
                              <span v-else>
                              {{ scope.row.hazard.cnName }}
                            </span>
                              <span
                                v-if="!scope.row.hazard.sampling.pointCount"
                                class="sampling-status"
                              >(不布点)</span>
                            </div>
                          </el-tag>
                        </template>
                        <span v-else>-</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="operationType === 2"
                    align="center"
                    label="操作"
                    width="80"
                  >
                    <template #default="scope">
                      <el-tooltip content="复制危害" placement="top">
                        <el-button
                          v-if="scope.row.hazard"
                          :icon="DocumentCopy"
                          link
                          type="primary"
                          @click="handleCopyHazard(scope.row, scope.row.hazard)"
                        />
                      </el-tooltip>
                      <el-tooltip content="删除危害" placement="top">
                        <el-button
                          v-if="scope.row.hazard"
                          :icon="Delete"
                          link
                          type="danger"
                          @click="handleDeleteHazardRow(scope.row, scope.row.hazard)"
                        />
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="operationType === 1" label="接触时机" width="150">
                    <template #default="scope">
                      <div v-if="scope.row.hazards?.[0]">
                        <el-input
                          v-model="scope.row.hazards[0].contactTiming"
                          :input-style="{ textAlign: 'center' }"
                          class="!w-full"
                          placeholder="请输入劳动者"
                          @change="(value) => handleContactTimingChange(scope.row, value)"
                        />
                      </div>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="operationType === 1" label="工作内容" width="150">
                    <template #default="scope">
                      <div v-if="scope.row.hazard">
                        <el-input
                          v-model="scope.row.hazard.workContent"
                          :input-style="{ textAlign: 'center' }"
                          class="!w-full"
                          @change="(value) => handleWorkContentChange(scope.row, value)"
                        />
                      </div>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="operationType === 1" label="来源">
                    <template #default="scope">
                      <div v-if="scope.row.hazard">
                        <el-input
                          v-model="scope.row.hazard.source"
                          :input-style="{ textAlign: 'center' }"
                          class="!w-full"
                          @change="(value) => handleSourceChange(scope.row, value)"
                        />
                      </div>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="operationType === 1 && hasHighTemperatureHazard"
                    class-name="col-storage-life"
                    label="劳动强度"
                    label-class-name="col-storage-life"
                    width="100"
                  >
                    <template #default="scope">
                      <div v-if="scope.row.hazard">
                        <el-select
                          v-model="scope.row.hazard.laborIntensity"
                          :input-style="{ textAlign: 'center' }"
                          class="!w-full"
                          placeholder="请选择"
                          @change="(value) => handleLaborIntensityChange(scope.row, value)"
                        >
                          <el-option label="I" value="1" />
                          <el-option label="II" value="2" />
                          <el-option label="III" value="3" />
                          <el-option label="IV" value="4" />
                        </el-select>
                      </div>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <!-- 新增接触频度列 -->
                  <el-table-column
                    v-if="operationType === 1 && hasUnstableContactType(position)"
                    label="接触频度"
                  >
                    <el-table-column label="次数" width="70">
                      <template #default="scope">
                        <el-input-number
                          v-model="scope.row.contactFrequency.count"
                          :min="0"
                          :controls="false"
                          size="small"
                          style="width: 100%"
                          @change="() => handleContactFrequencyChange(scope.row, 'count')"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="时间(h)" width="70">
                      <template #default="scope">
                        <el-input-number
                          v-model="scope.row.contactFrequency.duration"
                          :min="0"
                          :step="0.5"
                          :precision="1"
                          :controls="false"
                          size="small"
                          style="width: 100%"
                          @change="() => handleContactFrequencyChange(scope.row, 'duration')"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="间隔(h)" width="70">
                      <template #default="scope">
                        <el-input-number
                          v-model="scope.row.contactFrequency.interval"
                          :min="0"
                          :step="0.5"
                          :precision="1"
                          :controls="false"
                          size="small"
                          style="width: 100%"
                          @change="() => handleContactFrequencyChange(scope.row, 'interval')"
                        />
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <el-table-column label="接触时间(h)" width="80">
                    <template #default="scope">
                      <el-tooltip
                        v-if="hasUnstableContactType(position) && operationType === 1"
                        content="接触类型为非稳定时，接触时间由接触频度自动计算，请调整接触频度"
                        placement="top"
                      >
                        <el-input
                          v-model="scope.row.contactTime"
                          :disabled="true"
                          :input-style="{ textAlign: 'center' }"
                          :max="24"
                          :min="0"
                          :step="0.1"
                          class="!w-full"
                          placeholder="由频度计算"
                        />
                      </el-tooltip>
                      <el-input
                        v-else
                        v-model="scope.row.contactTime"
                        :input-style="{ textAlign: 'center' }"
                        :max="24"
                        :min="0"
                        :step="0.1"
                        class="!w-full"
                        @change="() => handleContactTimeChange(scope.row)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="operationType === 2"
                    align="center"
                    label="采样类型"
                    prop="sampleMethod"
                    width="90"
                  >
                    <template #default="scope">
                      <el-select
                        v-if="scope.row.hazard?.sampling"
                        v-model="scope.row.hazard.sampling.sampleType"
                        :disabled="true"
                        placeholder="请选择采样方式"
                        @change="() => handleSamplingChange(scope.row)"
                      >
                        <el-option label="定点" value="fix" />
                        <el-option label="个人" value="personal" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="operationType === 2 && columnVisible.testStandard"
                    align="center"
                    label="检测依据"
                    width="165px"
                  >
                    <template #default="scope">
                      <el-select
                        v-if="
                          scope.row.hazard?.testStandardList &&
                          scope.row.hazard.testStandardList.length
                        "
                        v-model="scope.row.hazard.testStandard"
                        :input-style="{ textAlign: 'center' }"
                        allow-create
                        class="!w-full"
                        default-first-option
                        filterable
                        placeholder="请选择或输入"
                      >
                        <el-option
                          v-for="standard in scope.row.hazard.testStandardList"
                          :key="standard"
                          :label="standard"
                          :value="standard"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="operationType === 2 && columnVisible.airCollector"
                    align="center"
                    label="空气收集器"
                    width="100"
                  >
                    <template #default="scope">
                      <el-select
                        v-if="
                          scope.row.hazard?.airCollectorList &&
                          scope.row.hazard.airCollectorList.length
                        "
                        v-model="scope.row.hazard.airCollector"
                        allow-create
                        clearable
                        default-first-option
                        filterable
                        placeholder="请选择或输入"
                        @change="(value) => handleAirCollectorChange(scope.row, value)"
                      >
                        <el-option
                          v-for="collector in scope.row.hazard.airCollectorList"
                          :key="collector"
                          :label="collector"
                          :value="collector"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="operationType === 2 && columnVisible.measuringEquipment"
                    align="center"
                    label="测量设备"
                    width="120"
                  >
                    <template #default="scope">
                      <el-select
                        v-if="
                          scope.row.hazard?.measuringEquipmentList &&
                          scope.row.hazard.measuringEquipmentList.length
                        "
                        v-model="scope.row.hazard.measuringEquipment"
                        :input-style="{ textAlign: 'center' }"
                        allow-create
                        class="!w-full"
                        default-first-option
                        filterable
                        placeholder="请选择或输入"
                      >
                        <el-option
                          v-for="equipment in scope.row.hazard.measuringEquipmentList"
                          :key="equipment"
                          :label="equipment"
                          :value="equipment"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="operationType === 2 && columnVisible.storageLife"
                    align="center"
                    label="保存期限"
                    width="100"
                  >
                    <template #default="scope">
                      <el-select
                        v-if="
                          scope.row.hazard?.storageLifeList &&
                          scope.row.hazard.storageLifeList.length
                        "
                        v-model="scope.row.hazard.storageLife"
                        :input-style="{ textAlign: 'center' }"
                        allow-create
                        class="!w-full"
                        default-first-option
                        filterable
                        placeholder="请选择或输入"
                      >
                        <el-option
                          v-for="storageLife in scope.row.hazard.storageLifeList"
                          :key="storageLife"
                          :label="storageLife"
                          :value="storageLife"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="operationType === 2 && columnVisible.flowRate"
                    align="center"
                    label="采样流量(L/min)"
                    width="70"
                  >
                    <template #default="scope">
                      <div v-if="scope.row.hazard?.sampling">
                        <el-input
                          v-model="scope.row.hazard.sampling.flowRate"
                          :input-style="{ textAlign: 'center' }"
                          :min="0"
                          class="!w-full"
                          @change="handleHazardSamplingChange(scope.row, 'flowRate')"
                        />
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column
                    v-if="operationType === 2"
                    align="center"
                    label="限值类型"
                    width="150"
                  >
                    <template #default="scope">
                      <el-select
                        v-if="scope.row.hazard?.sampling"
                        v-model="scope.row.hazard.sampling.strengthType"
                        :input-style="{ textAlign: 'center' }"
                        allow-create
                        class="!w-full"
                        clearable
                        default-first-option
                        filterable
                        placeholder="请选择或输入"
                        @change="(value) => handleStrengthTypeChange(scope.row, value)"
                        @focus="() => handleStrengthTypeFocus(scope.row)"
                      >
                        <el-option
                          v-for="option in currentStrengthTypeOptions.length > 0
                            ? currentStrengthTypeOptions
                            : strengthTypeOptions"
                          :key="option.value"
                          :label="option.label"
                          :value="option.value"
                        />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column v-if="operationType === 2" label="采样时长(min)" width="70">
                    <template #default="scope">
                      <div v-if="scope.row.hazard?.sampling">
                        <el-input
                          :input-style="{ textAlign: 'center' }"
                          :min="0"
                          :model-value="calculateSampleDuration(scope.row)"
                          class="!w-full"
                          @input="(value) => handleSampleDurationInput(scope.row, value)"
                        />
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column
                    v-if="operationType === 2"
                    align="center"
                    label="采样时间类型"
                    prop="longShortTime"
                    width="70"
                  >
                    <template #default="scope">
                      <el-select
                        v-if="scope.row.hazard?.sampling"
                        v-model="scope.row.hazard.sampling.timeType"
                        :input-style="{ textAlign: 'center' }"
                        class="!w-full"
                        clearable
                        placeholder="请选择长短时间"
                        @change="() => handleTimeTypeChange(scope.row)"
                      >
                        <el-option label="长" value="long" />
                        <el-option label="短" value="short" />
                        <el-option label="―" value="none" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="operationType === 2" label="点数" width="40">
                    <template #default="scope">
                      <div v-if="scope.row.hazard?.sampling">
                        <el-input
                          v-model="scope.row.hazard.sampling.pointCount"
                          :input-style="{ textAlign: 'center' }"
                          :min="1"
                          class="!w-full"
                          @change="handleHazardSamplingChange(scope.row, 'pointCount')"
                        />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="operationType === 2" label="每天次数" width="40">
                    <template #default="scope">
                      <div v-if="scope.row.hazard?.sampling">
                        <el-input
                          v-model="scope.row.hazard.sampling.sampleCount"
                          :input-style="{ textAlign: 'center' }"
                          :min="1"
                          class="!w-full"
                          @change="handleHazardSamplingChange(scope.row, 'sampleCount')"
                        />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="operationType === 2" label="采样天数" width="40">
                    <template #default="scope">
                      <div v-if="scope.row.hazard?.sampling">
                        <el-input
                          v-model="scope.row.hazard.sampling.sampleDays"
                          :input-style="{ textAlign: 'center' }"
                          :min="1"
                          class="!w-full"
                          @change="handleHazardSamplingChange(scope.row, 'sampleDays')"
                        />
                      </div>
                    </template>
                  </el-table-column>
                  <!--                  <el-table-column-->
                  <!--                    v-if="operationType === 2"-->
                  <!--                    align="center"-->
                  <!--                    label="样品编号"-->
                  <!--                    prop="sampleCode"-->
                  <!--                    width="90"-->
                  <!--                  />-->
                  <!-- 新增操作列 -->
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-else class="empty-state">
        <el-empty :description="'暂无车间信息，请点击「新增车间」按钮添加'" />
      </div>
    </ContentWrap>

    <!-- 添加新的组件引用 -->
    <HazardIdentificationDialog
      ref="hazardIdentificationRef"
      :operationType="operationType"
      :positionName="currentPositionName"
      :row="currentRow as any"
      @close="handleHazardDialogClose"
      @update="handleHazardUpdate"
    />
    <ImportHazardsDialog ref="importHazardsRef" @confirm="handleImportHazardsConfirm" />
    <!-- 设备布局对话框 -->
    <EquipmentLayoutDialog
      v-model:visible="equipmentLayoutDialogVisible"
      :projectId="route.query.projectId"
      @confirm="handleEquipmentLayoutConfirm"
    />

    <!-- 添加新增岗位类型选择弹窗 -->
    <el-dialog
      v-model="positionTypeDialogVisible"
      :title="isEditMode ? '编辑岗位' : '岗位管理'"
      class="position-management-dialog-wrapper"
      destroy-on-close
      width="60%"
    >
      <div class="position-management-dialog">
        <!-- 操作按钮区域 -->
        <div class="form-header">
          <div class="header-left">
            <el-button type="primary" @click="addNewPositionRow"> 添加岗位 </el-button>
          </div>
          <div class="header-right">
            <el-button @click="cancelPositionManagement">取消</el-button>
            <el-button type="primary" @click="confirmPositionManagement">确定</el-button>
          </div>
        </div>

        <!-- 岗位管理表单 -->
        <div class="position-form-container">
          <div
            v-for="(position, index) in allPositions"
            :key="position.id || index"
            :ref="isEditMode && position.id === editingPositionId ? 'editingPosition' : undefined"
            :class="{
              'editing-highlight': position.id === editingPositionId
            }"
            class="position-form"
            @click="handlePositionClick(position, $event)"
          >
            <div>
              <div v-if="operationType === 1" class="position-form-actions">
                <el-tooltip content="删除岗位" effect="light" placement="bottom">
                  <el-button
                    :icon="Delete"
                    circle
                    class="delete-position-btn"
                    text
                    @click.stop="onDeletePositionInForm(position, index)"
                  />
                </el-tooltip>
              </div>
              <el-form
                :model="position"
                class="position-form-grid"
                label-width="80px"
                style="
                  border: 1px solid #dcdfe6;
                  border-radius: 4px;
                  padding: 10px;
                  background: #fff;
                "
              >
                <el-row :gutter="20" class="form-row" style="margin-bottom: 2px">
                  <el-col :span="6">
                    <el-form-item label="岗位名称" required style="margin-bottom: 0 !important">
                      <el-input
                        :model-value="position.name"
                        placeholder="岗位名称"
                        size="small"
                        @update:model-value="
                          (value) => updatePositionField(position, index, 'name', value)
                        "
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label="作业类型" required>
                      <el-radio-group
                        :model-value="position.positionType"
                        size="small"
                        @update:model-value="
                          (value) => updatePositionField(position, index, 'positionType', value)
                        "
                      >
                        <el-radio :value="1">固定</el-radio>
                        <el-radio :value="2">流动</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label="接触类型" required>
                      <el-select
                        :model-value="position.workPosition"
                        placeholder="选择"
                        size="small"
                        @update:model-value="
                          (value) => updatePositionField(position, index, 'workPosition', value)
                        "
                      >
                        <el-option label="稳定" value="稳定" />
                        <el-option label="非稳定" value="非稳定" />
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label="总人数" required>
                      <el-input-number
                        :max="9999"
                        :min="1"
                        :model-value="position.totalPeople"
                        size="small"
                        @update:model-value="
                          (value) => updatePositionField(position, index, 'totalPeople', value)
                        "
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20" class="form-row" style="margin-bottom: 0">
                  <el-col :span="6">
                    <el-form-item label="数/班" required>
                      <el-input-number
                        :max="99"
                        :min="1"
                        :model-value="position.shiftCount"
                        size="small"
                        @update:model-value="
                          (value) => updatePositionField(position, index, 'shiftCount', value)
                        "
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="周工作天" required>
                      <el-input-number
                        :max="7"
                        :min="1"
                        :model-value="position.workDays"
                        size="small"
                        @update:model-value="
                          (value) => updatePositionField(position, index, 'workDays', value)
                        "
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="工作时间" required>
                      <el-input-number
                        :max="24"
                        :min="1"
                        :model-value="position.workHours"
                        size="small"
                        @update:model-value="
                          (value) => updatePositionField(position, index, 'workHours', value)
                        "
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label="班制" required>
                      <el-select
                        :model-value="position.shiftSystem"
                        allow-create
                        filterable
                        placeholder="选择"
                        size="small"
                        @update:model-value="
                          (value) => updatePositionField(position, index, 'shiftSystem', value)
                        "
                      >
                        <el-option
                          v-for="dict in getStrDictOptions(DICT_TYPE.SHIFT_DUTY)"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>

            <!-- 该岗位的工作地点表格 -->
            <div class="position-workplace-table">
              <div class="workplace-header">
                <div class="workplace-header-left">
                  <el-button
                    v-if="
                      position.positionType === 2 ||
                      !position.workplaceData ||
                      position.workplaceData.length === 0
                    "
                    size="small"
                    type="primary"
                    @click="addWorkplaceRowForPosition(position, index)"
                  >
                    添加地点
                  </el-button>
                  <span
                    v-if="
                      position.positionType === 1 &&
                      position.workplaceData &&
                      position.workplaceData.length > 0
                    "
                    class="fixed-position-tip"
                  >
                    固定作业类型只能添加一个工作地点
                  </span>
                </div>
                <div class="workplace-header-right">
                  <el-button
                    class="expand-btn"
                    size="small"
                    type="text"
                    @click="toggleWorkplaceExpanded(position.id)"
                  >
                    <el-icon>
                      <ArrowDown v-if="!isWorkplaceExpanded(position.id)" />
                      <ArrowUp v-else />
                    </el-icon>
                    {{ isWorkplaceExpanded(position.id) ? '收起' : '展开' }}工作地点
                  </el-button>
                </div>
              </div>

              <div v-show="isWorkplaceExpanded(position.id)" class="workplace-table-container">
                <el-table
                  :data="getWorkplaceDataForPosition(position)"
                  border
                  class="workplace-table"
                  empty-text="暂无工作地点信息"
                  size="small"
                >
                  <el-table-column label="车间" prop="workshop">
                    <template #default="{ row: workplaceRow, $index: workplaceIndex }">
                      <el-select
                        v-model="workplaceRow.workshop"
                        placeholder="请选择车间"
                        size="small"
                        @change="
                          handleWorkshopChangeForPosition(position, workplaceRow, workplaceIndex)
                        "
                      >
                        <el-option
                          v-for="workshop in availableWorkshops"
                          :key="workshop.id"
                          :label="workshop.name"
                          :value="workshop.name"
                        />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="工作地点" prop="workplace">
                    <template #default="{ row: workplaceRow, $index: workplaceIndex }">
                      <el-input
                        v-model="workplaceRow.workplace"
                        placeholder="请输入工作地点"
                        size="small"
                        @input="
                          handleWorkplaceChangeForPosition(position, workplaceRow, workplaceIndex)
                        "
                      />
                    </template>
                  </el-table-column>

                  <el-table-column label="接触时间(h)" prop="contactTime">
                    <template #default="{ row: workplaceRow, $index: workplaceIndex }">
                      <el-tooltip
                        v-if="position.workPosition === '非稳定'"
                        content="接触类型为非稳定时，接触时间由接触频度自动计算，请调整接触频度"
                      >
                        <el-input-number
                          v-model="workplaceRow.contactTime"
                          :disabled="true"
                          :max="24"
                          :min="0"
                          :step="0.1"
                          controls-position="right"
                          placeholder="由频度计算"
                          size="small"
                        />
                      </el-tooltip>
                      <el-input-number
                        v-else
                        v-model="workplaceRow.contactTime"
                        :max="
                          position.workPosition === '稳定' ? Number(position.workHours) || 24 : 24
                        "
                        :min="0"
                        :step="0.1"
                        controls-position="right"
                        size="small"
                        @change="
                          () =>
                            handleWorkplaceContactTimeInputChange(
                              position,
                              workplaceRow,
                              workplaceIndex
                            )
                        "
                      />
                    </template>
                  </el-table-column>

                  <!-- 接触频度列 - 只有当岗位接触类型为"非稳定"时才显示 -->
                  <el-table-column v-if="position.workPosition === '非稳定'" label="接触频度">
                    <el-table-column label="次数" width="80">
                      <template #default="{ row: workplaceRow, $index: workplaceIndex }">
                        <el-input-number
                          v-model="workplaceRow.contactFrequency.count"
                          :min="0"
                          controls-position="right"
                          size="small"
                          @change="
                            handleWorkplaceContactFrequencyChange(
                              position,
                              workplaceRow,
                              workplaceIndex,
                              'count'
                            )
                          "
                          @focus="
                            handleWorkplaceFrequencyFocus(
                              position,
                              workplaceRow,
                              workplaceIndex,
                              'count'
                            )
                          "
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="时间(h)" width="80">
                      <template #default="{ row: workplaceRow, $index: workplaceIndex }">
                        <el-input-number
                          v-model="workplaceRow.contactFrequency.duration"
                          :min="0"
                          :step="0.1"
                          controls-position="right"
                          size="small"
                          @change="
                            handleWorkplaceContactFrequencyChange(
                              position,
                              workplaceRow,
                              workplaceIndex,
                              'duration'
                            )
                          "
                          @focus="
                            handleWorkplaceFrequencyFocus(
                              position,
                              workplaceRow,
                              workplaceIndex,
                              'duration'
                            )
                          "
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="间隔(h)" width="80">
                      <template #default="{ row: workplaceRow, $index: workplaceIndex }">
                        <el-input-number
                          v-model="workplaceRow.contactFrequency.interval"
                          :min="0"
                          :step="0.1"
                          controls-position="right"
                          size="small"
                          @change="
                            handleWorkplaceContactFrequencyChange(
                              position,
                              workplaceRow,
                              workplaceIndex,
                              'interval'
                            )
                          "
                          @focus="
                            handleWorkplaceFrequencyFocus(
                              position,
                              workplaceRow,
                              workplaceIndex,
                              'interval'
                            )
                          "
                        />
                      </template>
                    </el-table-column>
                  </el-table-column>

                  <el-table-column fixed="right" label="操作" width="60">
                    <template #default="{ $index: workplaceIndex }">
                      <el-button
                        link
                        size="small"
                        type="danger"
                        @click="deleteWorkplaceRowForPosition(position, workplaceIndex)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 添加新的 ref 变量 -->
    <!-- 修改后的新增车间弹窗 -->
    <!-- 新增车间弹窗 (两列布局美化版) -->
    <el-dialog
      v-model="workshopDialogVisible"
      title="新增车间"
      width="550px"
      destroy-on-close
      class="workshop-add-dialog"
      top="8vh"
    >
      <!-- 顶部：默认参数设置区域 -->
      <div class="dialog-defaults-wrapper">
        <div class="defaults-header">
          <span class="title">默认参数配置</span>
          <span class="subtitle">（应用于本次新建的所有车间）</span>
        </div>

        <div class="defaults-content">
          <!-- 使用 Grid 布局实现一行两个 -->
          <div class="defaults-grid">
            <!-- 2. 周工作 -->
            <div class="default-item">
              <span class="item-label">周工作(d)</span>
              <el-input-number
                v-model="defaultWorkDays"
                :max="8"
                :min="0"
                size="default"
                controls-position="right"
                style="width: 100%"
              />
            </div>
            <!-- 1. 日工作 -->
            <div class="default-item">
              <span class="item-label">日工作(h)</span>
              <el-input-number
                v-model="defaultWorkHours"
                :max="24"
                :min="0"
                :precision="1"
                :step="0.5"
                size="default"
                controls-position="right"
                style="width: 100%"
              />
            </div>
            <!-- 3. 班制 -->
            <div class="default-item">
              <span class="item-label">班制</span>
              <el-select
                v-model="defaultShiftSystem"
                allow-create
                filterable
                size="default"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.SHIFT_DUTY)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </div>

            <!-- 4. 时段设置 -->
            <div class="default-item">
              <span class="item-label">工作时段</span>
              <el-button
                class="time-setting-btn"
                type="primary"
                link
                bg
                @click="openWorkTimeDialog"
              >
                <el-icon class="mr-1"><Clock /></el-icon>
                设置时段
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 中部：车间列表表单 -->
      <div class="workshop-list-header">
        <span>车间名称列表</span>
        <el-button type="primary" link size="small" @click="addWorkshopRow(workshopList.length)">
          <el-icon class="mr-1"><Plus /></el-icon> 添加一行
        </el-button>
      </div>

      <div class="workshop-list-scroll">
        <el-form @submit.prevent>
          <transition-group name="list-transition">
            <div v-for="(item, idx) in workshopList" :key="item.id || idx" class="workshop-row">
              <div class="row-index">{{ idx + 1 < 10 ? '0' + (idx + 1) : idx + 1 }}</div>
              <el-input
                v-model="item.name"
                class="workshop-input"
                maxlength="50"
                placeholder="请输入车间名称"
                show-word-limit
                @keyup.enter="addWorkshopRow(idx)"
              />
              <div class="row-actions">
                <el-button
                  type="primary"
                  plain
                  circle
                  size="small"
                  :icon="Plus"
                  @click="addWorkshopRow(idx)"
                />
                <el-button
                  type="danger"
                  plain
                  circle
                  size="small"
                  :icon="Delete"
                  :disabled="workshopList.length <= 1"
                  @click="removeWorkshopRow(idx)"
                />
              </div>
            </div>
          </transition-group>
        </el-form>

        <div v-if="workshopList.length === 0" class="empty-tip">
          点击上方按钮添加车间
        </div>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer-custom">
          <div class="footer-left">
            <span class="summary">共 <b>{{ workshopList.length }}</b> 个车间</span>
          </div>
          <div class="footer-right">
            <el-button @click="workshopDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmAddWorkshop">确 定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 添加新的 ref 变量 -->
    <el-dialog
      v-model="editWorkshopDialogVisible"
      :title="'修改车间名称'"
      destroy-on-close
      width="500px"
    >
      <el-form :model="{ name: editingWorkshopName }" label-width="80px">
        <el-form-item
          :rules="[
            { required: true, message: '请输入车间名称', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
          ]"
          label="车间名称"
        >
          <el-input
            v-model="editingWorkshopName"
            maxlength="50"
            placeholder="请输入车间名称"
            show-word-limit
            @keyup.enter="confirmEditWorkshop"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editWorkshopDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditWorkshop">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editPositionDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      style="border-radius: 0; box-shadow: none"
      title="修改岗位名称"
      width="350px"
    >
      <el-input
        v-model="editingPositionName"
        maxlength="50"
        placeholder="请输入岗位名称"
        show-word-limit
        style="border-radius: 0"
        @keyup.enter="confirmEditPosition"
      />
      <template #footer>
        <el-button @click="editPositionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEditPosition">确定</el-button>
      </template>
    </el-dialog>
    <!-- 工作时段维护弹窗 -->
    <el-dialog
      v-model="workTimeDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="工作时段设置"
      width="600px"
    >
      <div class="work-time-dialog">
        <!-- 班制选择 -->
        <div class="shift-system-section">
          <span class="section-label">班制：</span>
          <el-select
            v-model="editingShiftSystem"
            allow-create
            filterable
            size="default"
            style="width: 150px"
            @change="handleEditingShiftSystemChange"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.SHIFT_DUTY)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <span class="shift-info"> 当前工作时间: {{ workHours }}小时/天 </span>
        </div>

        <!-- 时段列表 -->
        <div class="time-segments-section">
          <div class="section-header">
            <span class="section-label">工作时段：</span>
            <el-button size="small" type="primary" @click="addTimeSegment"> 添加时段 </el-button>
          </div>

          <div class="segments-list">
            <div
              v-for="(segment, index) in editingWorkTimeSegments"
              :key="segment.id"
              class="segment-item"
            >
              <span class="segment-index">第{{ index + 1 }}段：</span>

              <el-time-picker
                v-model="segment.startTime"
                format="HH:mm"
                placeholder="开始时间"
                size="default"
                style="width: 120px"
                value-format="HH:mm"
                @change="calculateSegmentDuration(segment)"
              />

              <span class="time-separator">-</span>

              <el-time-picker
                v-model="segment.endTime"
                format="HH:mm"
                placeholder="结束时间"
                size="default"
                style="width: 120px"
                value-format="HH:mm"
                @change="calculateSegmentDuration(segment)"
              />

              <span class="duration-display"> {{ segment.duration.toFixed(1) }}小时 </span>

              <el-button
                :disabled="editingWorkTimeSegments.length <= 1"
                plain
                size="small"
                type="danger"
                @click="removeTimeSegment(index)"
              >
                删除
              </el-button>
            </div>
          </div>

          <!-- 总时长验证 -->
          <div class="total-duration-section">
            <div class="total-info">
              <span>总时长：{{ getTotalDuration() }}小时</span>
              <span class="target-duration">/ 目标：{{ workHours }}小时</span>
            </div>
            <div v-if="Math.abs(getTotalDuration() - workHours) > 0.1" class="duration-warning">
              ⚠️ 总时长与工作时间不一致，请调整时段设置
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelWorkTimeDialog">取消</el-button>
          <el-button
            :disabled="Math.abs(getTotalDuration() - defaultWorkHours) > 0.1"
            type="primary"
            @click="confirmWorkTimeDialog"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 布点维护弹窗 -->
    <el-dialog
      v-model="pointMaintainDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="布点维护"
      width="720px"
    >
      <div v-if="pointMaintainRow">
        <div style="margin-bottom: 12px">
          <span>限值类型：</span>
          <el-checkbox-group v-model="pointMaintainStrengthTypes">
            <el-checkbox :label="1">PC-TWA</el-checkbox>
            <el-checkbox :label="2">PC-STEL</el-checkbox>
            <el-checkbox :label="4">PE</el-checkbox>
          </el-checkbox-group>
        </div>
        <div>
          <span>危害选择：</span>
          <el-checkbox-group v-model="pointMaintainHazardIds">
            <el-checkbox
              v-for="hz in pointMaintainHazards"
              :key="hz.id"
              :label="String(hz.id ?? hz.cnName)"
            >
              {{ hz.cnName }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <template #footer>
        <el-button @click="pointMaintainDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPointMaintain">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import type { Directive } from 'vue'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown, ArrowUp, Close, Delete, DocumentCopy, Edit, Plus, PriceTag, Setting, Clock
} from '@element-plus/icons-vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import HazardIdentificationDialog from './HazardIdentificationDialog.vue'
import ImportHazardsDialog from './ImportHazardsDialog.vue'
import EquipmentLayoutDialog from './EquipmentLayoutDialog.vue'
import {
  Hazard,
  PositionBlock,
  TabItem,
  TableItem,
  useSurveyStore,
  WorkTimeSegment
} from '@/store/modules/survey'
import { useRoute, useRouter } from 'vue-router'
import { HazardsApi } from '@/api/system/hazards'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'
import { v4 as uuidv4 } from 'uuid'

const router = useRouter()
// 获取路由对象
const route = useRoute()
// 使用 defineProps 来声明 props
// 1 调查  2方案
const props = defineProps({
  operationType: {
    type: Number,
    default: 2
  }
})


// 辅助函数：解析班制字符串为数字
const parseShiftSystemValue = (shiftSystem: string | number): number => {
  if (!shiftSystem) return 1
  if (typeof shiftSystem === 'number') return shiftSystem

  // 如果字符串开头是数字（如 "3班"），直接解析
  const floatVal = parseFloat(shiftSystem)
  if (!isNaN(floatVal)) return floatVal

  // 匹配中文数字
  if (shiftSystem.includes('一')) return 1
  if (shiftSystem.includes('二') || shiftSystem.includes('两')) return 2
  if (shiftSystem.includes('三')) return 3
  if (shiftSystem.includes('四')) return 4
  if (shiftSystem.includes('五')) return 5
  if (shiftSystem.includes('六')) return 6
  if (shiftSystem.includes('七')) return 7
  if (shiftSystem.includes('八')) return 8

  // 默认返回 1，避免计算为 0 或 NaN
  return 1
}

// 计算总人数的通用方法
const calculateTotalPeople = (position: any) => {
  const shiftCount = Number(position.shiftCount) || 0
  const shiftValue = parseShiftSystemValue(position.shiftSystem)

  // 计算总人数 = 数/班 * 班制数值
  position.totalPeople = shiftCount * shiftValue
}

const confirmPointMaintain = () => {
  const row = pointMaintainRow.value
  if (!row) {
    pointMaintainDialogVisible.value = false
    return
  }
  if (
    !Array.isArray(pointMaintainHazardIds.value) ||
    !pointMaintainHazardIds.value.length ||
    !Array.isArray(pointMaintainStrengthTypes.value) ||
    !pointMaintainStrengthTypes.value.length
  ) {
    pointMaintainDialogVisible.value = false
    return
  }

  const selectedIds = new Set(pointMaintainHazardIds.value.map((v) => String(v)))
  const selectedStrengthTypes = new Set(pointMaintainStrengthTypes.value)

  // 只处理当前工位行的 hazards
  if (Array.isArray(row.hazards)) {
    row.hazards.forEach((hz: any) => {
      const key = String(hz.id ?? hz.cnName)
      if (!selectedIds.has(key)) return
      if (!hz.sampling) return
      if (!selectedStrengthTypes.has(Number(hz.sampling.strengthType))) return

      // 当前危害点位 = 0
      hz.sampling.pointCount = 0
    })
  }

  // 只刷新这一岗位的 tableData，避免全局联动
  const position = findPositionByRow(row)
  if (position) {
    position.tableData = [...position.tableData]
  }

  pointMaintainDialogVisible.value = false
}

const openPointMaintainDialog = (row: any) => {
  console.log('openPointMaintainDialog',JSON.stringify( row))
  if (!row || !Array.isArray(row.hazards) || !row.hazards.length) {
    ElMessage.warning('当前工位没有危害，无法布点维护')
    return
  }
  pointMaintainRow.value = row
  // 当前工位所有危害（可按 id 或 cnName 去重）
  const map: Record<string, any> = {}
  row.hazards.forEach((hz: any) => {
    const key = String(hz.id ?? hz.cnName)
    if (!map[key]) map[key] = hz
  })
  pointMaintainHazards.value = Object.values(map)
  // 默认限值 1/2/3 全选
  pointMaintainStrengthTypes.value = [1, 2, 4]
  // 默认当前工位所有危害全选
  pointMaintainHazardIds.value = pointMaintainHazards.value.map((hz: any) =>
    String(hz.id ?? hz.cnName)
  )
  pointMaintainDialogVisible.value = true
}
// 去重：同一行内按危害名称唯一化用于显示（operationType=1）
const getUniqueHazardsByName = (hazards: any[] = []) => {
  const seen = new Set<string>()
  const result: any[] = []
  for (const h of hazards) {
    const name = (h?.cnName ?? '').toString()
    if (!name) continue
    if (!seen.has(name)) {
      seen.add(name)
      result.push(h)
    }
  }
  return result
}

// --- START: 新增代码 ---

// 1. 正式的、控制表格列是否渲染的响应式变量 (v-if 会用到)
const columnVisible = ref({
  testStandard: false,
  airCollector: false,
  measuringEquipment: false,
  storageLife: false,
  flowRate: false
})

// 2. 临时的、用于 Popover 内 Checkbox 双向绑定的“草稿”变量
const tempColumnVisible = ref({ ...columnVisible.value })

// 3. 用于存储 Popover 实例的 Map (实现高性能命令式控制)
const popoverRefs = new Map()
let currentPopoverPositionId: string | null = null // 非响应式，仅用于追踪

// 4. 在模板中绑定 ref 的函数
const setPopoverRef = (el: any, positionId: string) => {
  if (el) {
    popoverRefs.set(positionId, el)
  } else {
    // 组件卸载时移除引用，防止内存泄漏
    popoverRefs.delete(positionId)
  }
}

// 5. 点击“列设置”按钮的触发函数
const togglePopover = (positionId: string) => {
  // 记录当前点击的是哪个岗位的 Popover
  currentPopoverPositionId = positionId
  // 【关键】: 在 Popover 打开前，用当前的正式设置来初始化临时“草稿”
  tempColumnVisible.value = { ...columnVisible.value }
}

// 6. 点击“取消”按钮的函数
const cancelColumnSettings = () => {
  if (currentPopoverPositionId) {
    const popoverInstance = popoverRefs.get(currentPopoverPositionId)
    popoverInstance?.hide() // 调用实例方法关闭
    currentPopoverPositionId = null // 清理追踪
  }
}

// 7. 点击“确定”按钮的函数
const confirmColumnSettings = () => {
  // 将“草稿”设置应用到正式设置上
  columnVisible.value = { ...tempColumnVisible.value }

  if (currentPopoverPositionId) {
    const popoverInstance = popoverRefs.get(currentPopoverPositionId)
    popoverInstance?.hide() // 调用实例方法关闭
    currentPopoverPositionId = null // 清理追踪
  }
}
// 吸顶表头：本地指令 v-sticky-header（克隆表头到 body，兼容外层滚动容器）
type StickyBinding = number | { offset?: number }
const vStickyHeader: Directive<HTMLElement, StickyBinding> = {
  mounted(el, binding) {
    const getOffset = () => {
      const val = binding.value as StickyBinding
      if (typeof val === 'number') return val
      if (val && typeof val.offset === 'number') return val.offset
      return 0
    }

    const headerWrapper = el.querySelector<HTMLElement>('.el-table__header-wrapper')
    const headerTable = el.querySelector<HTMLTableElement>('.el-table__header-wrapper table')
    if (!headerWrapper || !headerTable) return

    const overlay = document.createElement('div')
    overlay.className = 'dk-sticky-table-header'
    overlay.style.position = 'fixed'
    overlay.style.top = `${getOffset()}px`
    overlay.style.left = '0px'
    overlay.style.zIndex = '2000'
    overlay.style.background = 'var(--el-bg-color, #fff)'
    overlay.style.boxShadow = '0 2px 6px rgba(0,0,0,0.06)'
    overlay.style.display = 'none'
    overlay.style.pointerEvents = 'none'
    document.body.appendChild(overlay)

    const buildClone = () => {
      overlay.innerHTML = ''
      const clone = headerTable.cloneNode(true) as HTMLTableElement
      const origTh = headerTable.querySelectorAll('th')
      const cloneTh = clone.querySelectorAll('th')
      const count = Math.min(origTh.length, cloneTh.length)
      for (let i = 0; i < count; i++) {
        const w = (origTh[i] as HTMLElement).getBoundingClientRect().width
        const cth = cloneTh[i] as HTMLElement
        cth.style.width = w + 'px'
        cth.style.minWidth = w + 'px'
        cth.style.maxWidth = w + 'px'
      }
      overlay.appendChild(clone)
    }

    const updateLayout = () => {
      const rect = el.getBoundingClientRect()
      overlay.style.left = rect.left + 'px'
      overlay.style.width = rect.width + 'px'
      overlay.style.top = `${getOffset()}px`
    }

    const getHeaderHeight = () => headerWrapper.getBoundingClientRect().height

    const onScroll = () => {
      const rect = el.getBoundingClientRect()
      const hh = getHeaderHeight()
      const offset = getOffset()
      if (rect.top <= offset && rect.bottom - hh > offset) {
        if (overlay.style.display !== 'block') {
          buildClone()
          overlay.style.display = 'block'
        }
        updateLayout()
      } else {
        if (overlay.style.display !== 'none') overlay.style.display = 'none'
      }
    }

    const onResize = () => {
      if (overlay.style.display === 'block') {
        buildClone()
        updateLayout()
      }
    }

    const getScrollParents = (node: HTMLElement): (Window | HTMLElement)[] => {
      const parents: (Window | HTMLElement)[] = [window]
      let p: HTMLElement | null = node.parentElement
      const regex = /(auto|scroll)/i
      while (p && p !== document.body) {
        const style = window.getComputedStyle(p)
        if (regex.test(style.overflowY) || regex.test(style.overflow)) parents.push(p)
        p = p.parentElement
      }
      return parents
    }

    const parents = getScrollParents(el)
    parents.forEach((sp) => sp.addEventListener('scroll', onScroll, { passive: true } as any))
    window.addEventListener('resize', onResize)
    ;(el as any).__stickyHeader__ = { overlay, onScroll, onResize, parents }

    // 初次计算
    onScroll()
  },
  updated(el) {
    const state = (el as any).__stickyHeader__
    if (!state) return
    state.onScroll()
  },
  unmounted(el) {
    const state = (el as any).__stickyHeader__
    if (state) {
      state.parents.forEach((sp: any) => sp.removeEventListener('scroll', state.onScroll))
      window.removeEventListener('resize', state.onResize)
      if (state.overlay && state.overlay.parentNode)
        state.overlay.parentNode.removeChild(state.overlay)
    }
    delete (el as any).__stickyHeader__
  }
}

// 顶部偏移（如存在固定导航条可在此配置高度）
const stickyHeaderOptions = computed(() => ({ offset: 0 }))

const lableName = computed(() => {
  return props.operationType === 1 ? '工作地点' : '采样对象/采样点'
})

// 检查当前活动标签页是否包含高温危害
const hasHighTemperatureHazard = computed(() => {
  if (!tabList.value || tabList.value.length === 0) return false

  const currentTab = tabList.value.find((tab) => tab.id === activeTab.value)
  if (!currentTab || !currentTab.positions) return false

  console.log('检查高温危害 - 当前标签页:', currentTab.name)

  // 遍历当前标签页的所有岗位
  for (const position of currentTab.positions) {
    if (!position.tableData) continue
    // 遍历岗位的表格数据
    for (const row of position.tableData) {
      // 检查 operationType === 1 的情况（调查模式）
      if (props.operationType === 1 && row.hazards && row.hazards.length > 0) {
        for (const hazard of row.hazards) {
          if (hazard.cnName && hazard.cnName.includes('高温')) {
            console.log('发现高温危害，显示劳动强度列')
            return true
          }
        }
      }
    }
  }

  console.log('未发现高温危害，隐藏劳动强度列')
  return false
})

const tosketch = () => {
  // 打开设备布局对话框
  equipmentLayoutDialogVisible.value = true
}

// 设备布局对话框处理方法
const handleEquipmentLayoutConfirm = (data: any[]) => {
  console.log('设备布局数据保存成功', JSON.stringify(data))
  ElMessage.success('设备布局保存成功')
}

/** 添加开始调查方法 */
const toPreviewJobSurvey = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 2
    }
  })
}

// 添加必要的类型定义
interface LocalHazard {
  id: number
  type: number // 危害类型
  cnName: string
  letter?: string
  contactTime?: string
  workContent?: string
  laborIntensity?: string
  source?: string
  sampling?: {
    sampleDays: number
    pointCount: number
    sampleCount: number
    contactHours: number
    startDay: number
    timeType: 'long' | 'short' | 'none'
    sampleType: 'fix' | 'personal' | 'none'
    isCustomTime?: boolean
    sampleDuration?: number
    flowRate?: number
    strengthType?: number
  }
  contactFrequency?: {
    count: number
    duration: number
    interval: number
  }
  personalProtection?: string
  personalProtectionList?: string[]
  personalProtectionIds?: number[]
  protectiveFacilities?: string
  protectiveFacilitiesList?: string[]
  protectiveFacilitiesIds?: number[]
  fluctuationTime?: string
  remark?: string
  airCollector?: string
  airCollectorList?: string[]
  airCollectorIds?: number[]
  workLocation?: number | string
  testStandard?: string
  testStandardList?: string[]
  measuringEquipment?: string
  measuringEquipmentList?: string[]
  storageLife?: string
  storageLifeList?: string[]
}

interface ExpandedTableItem extends TableItem {
  hazard?: LocalHazard
  isFirstHazard: boolean
  hazardCount: number
  originalId: string
  // 新增：用于工位维度合并测量号
  isFirstPositionRow?: boolean
  positionRowSpan?: number
}

const surveyStore = useSurveyStore()

// 使用 store 中的状态
const tabList = computed(() => surveyStore.tabList)
const activeTab = computed({
  get: () => surveyStore.activeTab,
  set: (value) => surveyStore.updateActiveTab(value)
})

// 根据岗位名称获取包含该岗位的所有车间名称（数组）
const getWorkshopNamesForPositionList = (positionName: string): string[] => {
  const names: string[] = []
  try {
    if (!positionName) return names
    const tabs = tabList.value as unknown as TabItem[]
    if (!tabs || tabs.length === 0) return names
    for (const tab of tabs) {
      const posList = tab.positions || []
      if (posList.some((p: any) => !p?.isDeleted && p?.name === positionName)) {
        if (!names.includes(tab.name)) names.push(tab.name)
      }
    }
    return names
  } catch (e) {
    return names
  }
}

// 添加一个强制刷新的响应式变量
const forceRefreshKey = ref(0)
const forceRefresh = () => {
  forceRefreshKey.value++
  console.log('强制刷新表格数据，key:', forceRefreshKey.value)
}

// 当前过滤后的限值类型选项
const currentStrengthTypeOptions = ref<DictOption[]>([])

// 添加字典选项接口
interface DictOption {
  value: number
  label: string
}

const inputRef = ref()

// 防护选择相关
const currentRow = ref<ExpandedTableItem | null>(null)

// 危害识别相关
const hazardIdentificationRef = ref()
const currentPositionName = ref<string>('')
// 导入危害相关
const importHazardsRef = ref()
const currentImportRow = ref<any>(null)
// 工位显示文本（去除 HTML 标签）
const formatWorkRowLabel = (testItem: string) => {
  try {
    return (testItem || '').replace(/<[^>]+>/g, '')
  } catch {
    return testItem
  }
}

// 打开导入危害弹窗
const openImportHazards = (row: any) => {
  if (!row) return
  currentImportRow.value = row
  // 【修改点】：将 row 传递给 open 方法
  importHazardsRef.value?.open(row)
}

// 处理导入危害确认
const handleImportHazardsConfirm = async (payload: any) => {
  console.log('📦 [导入] 收到 Payload:', payload)

  // ==================================================================================
  // 场景 A: 批量导入模式 (ImportHazardsDialog 返回 targetRowIds)
  // ==================================================================================
  if (payload && payload.targetRowIds && Array.isArray(payload.targetRowIds)) {
    const rowIds = payload.targetRowIds
    console.log(`🚀 [批量导入] 处理 ${rowIds.length} 个受影响的工位`)

    for (const rowId of rowIds) {
      const position = findPositionByRow({ id: rowId })
      if (!position) continue
      const targetRow = position.tableData.find((r) => r.id === rowId)
      if (!targetRow) continue

      // 1. 工位行内去重
      if (targetRow.hazards && targetRow.hazards.length > 1) {
        const uniqueMap = new Map()
        const uniqueHazards: Hazard[] = []
        targetRow.hazards.forEach((h) => {
          // 使用 ID 或 名称去重
          const key = h.id ? String(h.id) : h.cnName
          if (!uniqueMap.has(key)) {
            uniqueMap.set(key, true)
            uniqueHazards.push(h)
          }
        })
        targetRow.hazards = uniqueHazards
      }

      // 2. 【修改点】不再手动同步劳动者，直接触发核心重算逻辑
      // 让 handleHazardUpdate 统一处理“流动岗位补全”、“劳动者同步”等规则
      currentRow.value = targetRow
      await recalculateRowHazards(targetRow)
    }

    ElMessage.success(`导入成功，已更新 ${rowIds.length} 个工位及其关联数据`)
    refreshAllTables()
    return
  }

  // ==================================================================================
  // 场景 B: 单条/手动选择模式 (Payload 是危害数组)
  // ==================================================================================

  // 1. 数据提取
  let hazards: Hazard[] = []
  if (Array.isArray(payload)) {
    hazards = payload
  } else if (payload && typeof payload === 'object') {
    hazards = payload.hazards || payload.list || payload.selected || []
  }
  if (hazards.length === 0) return

  // 2. 基础定位
  if (!currentImportRow.value) return
  const position = findPositionByRow(currentImportRow.value)
  if (!position) return
  const targetRowId = currentImportRow.value.originalId || currentImportRow.value.id
  const targetRow = position.tableData.find((r) => r.id === targetRowId)
  if (!targetRow) return

  // 3. 准备当前已有数据
  const workingHazards: any[] = JSON.parse(JSON.stringify(targetRow.hazards || []))
  const rowContactTime = typeof targetRow.contactTime === 'string'
    ? parseFloat(targetRow.contactTime || '0') : (targetRow.contactTime as any) || 0

  // 4. 【关键】API 获取详情 (确保导入的数据包含 流量/MAC/TWA 等核心字段)
  const detailsMap = new Map<number, any>()
  // 并发请求提高速度
  await Promise.all(hazards.map(async (hz) => {
    try {
      const detail = await HazardsApi.getHazards(hz.id)
      detailsMap.set(hz.id, { ...hz, ...detail }) // 合并详情
    } catch (e) {
      detailsMap.set(hz.id, hz)
    }
  }))

  // 5. 构造待添加列表 (去重)
  const toAppend: Hazard[] = []
  const existingIds = new Set(workingHazards.map((h) => String(h.id)))

  for (const hz of hazards) {
    const full = detailsMap.get(hz.id) || hz

    if (!existingIds.has(String(full.id))) {
      const newHz = {
        ...full,
        workLocation: targetRow.workLocation,
        operationType: props.operationType,
        // 自动生成来源
        source: `${formatWorkRowLabel(targetRow.testItem)}时产生${full.cnName}`,
        sampling: {
          sampleDays: 1, pointCount: 1, sampleCount: 1, contactHours: rowContactTime,
          startDay: 1,
          // 默认给长时，具体类型由 handleHazardUpdate 根据岗位模式决定
          timeType: 'long',
          sampleType: targetRow.workLocation === 1 ? 'fix' : 'personal',
          isCustomTime: false, sampleDuration: 0, flowRate: 0, strengthType: 1
        }
      }
      // 预设一些默认值，但最终由 Update 逻辑修正
      if (String(newHz.type) === '2') {
        // 简单的默认值，后续 Update 会根据是否有 MAC/TWA 覆盖它
        newHz.sampling.strengthType = 1
        newHz.sampling.flowRate = 10
      }

      toAppend.push(newHz)
      existingIds.add(String(full.id))
    }
  }

  // 6. 【修改点】删除手动同步劳动者的代码块
  // 原有的 if (targetRow.workLocation === 1) { ... } 逻辑已移除
  // 统一由 handleHazardUpdate 处理

  // 7. 合并并触发核心引擎
  const finalHazards = [...workingHazards, ...toAppend]
  currentRow.value = targetRow as any

  // 调用核心逻辑，它会处理：拆分 TWA/STEL、流动岗位逻辑、同步劳动者
  await handleHazardUpdate(finalHazards)

  position.tableData = [...position.tableData]
  forceRefresh()

  if (toAppend.length > 0) {
    ElMessage.success(`已导入 ${toAppend.length} 个危害`)
  } else {
    ElMessage.info('危害已更新')
  }
  currentImportRow.value = null
}

// 设备布局对话框相关
const equipmentLayoutDialogVisible = ref(false)

// 使用 computed 来处理选项数据，并确保没有重复和 null 值
const strengthTypeOptions = computed<DictOption[]>(() => {
  const options = getIntDictOptions(DICT_TYPE.CITYPE)
  const processedValues = new Set<number>()
  const uniqueOptions: DictOption[] = []

  for (const option of options) {
    if (option.value == null || processedValues.has(option.value)) {
      continue
    }

    processedValues.add(option.value)
    uniqueOptions.push({
      value: option.value,
      label: option.label || `选项${option.value}`
    })
  }

  return uniqueOptions.sort((a, b) => a.value - b.value)
})

// 处理限值类型选择器获得焦点事件
const handleStrengthTypeFocus = (row: ExpandedTableItem) => {
  if (!row.hazard || !row.hazard.sampling) {
    currentStrengthTypeOptions.value = strengthTypeOptions.value
    return
  }

  // 获取完整的危害数据
  const hazard = getCompleteHazardData(row)
  const filteredOptions = filterStrengthTypeOptions(hazard)

  // 更新当前选项
  currentStrengthTypeOptions.value = filteredOptions

  console.log(`[限值类型过滤] 危害: ${hazard.cnName}, 过滤后选项数量: ${filteredOptions.length}`)
}

// 处理限值类型变化事件
const handleStrengthTypeChange = (row: ExpandedTableItem, value: number) => {
  if (!row.hazard || !row.hazard.sampling) return

  // 根据限值类型设置采样时间类型
  // 限值类型为1时，采样时间类型为long；否则为short
  const newTimeType = value === 1 ? 'long' : 'short'
  row.hazard.sampling.timeType = newTimeType

  console.log(
    `[限值类型变化] 危害: ${row.hazard.cnName}, 限值类型: ${value}, 采样时间类型: ${newTimeType}`
  )

  // 同步到原始数据
  const position = findPositionByRow(row)
  if (!position) return

  const originalRowId = row.originalId
  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) return

  const hazardId = row.hazard.id
  const hazardIndex = originalRow.hazards.findIndex((h) => h.id === hazardId)
  if (hazardIndex === -1) return

  if (originalRow.hazards[hazardIndex].sampling) {
    originalRow.hazards[hazardIndex].sampling.strengthType = value
    originalRow.hazards[hazardIndex].sampling.timeType = newTimeType
  }

  // 强制更新表格数据
  position.tableData = [...position.tableData]

  // 接触时间 < 1 时，确保 workLocation=2 不保留 type=1/2/3 的危害
  try {
    const ctFinal =
      typeof originalRow.contactTime === 'string'
        ? parseFloat(originalRow.contactTime || '0')
        : originalRow.contactTime || 0
    if (ctFinal < 1) {
      const laborerRows = position.tableData.filter((row: any) => row.workLocation === 2)
      laborerRows.forEach((row: any) => {
        if (Array.isArray(row.hazards) && row.hazards.length > 0) {
          row.hazards = row.hazards.filter((h: any) => {
            const t = String((h as any)?.type)
            return t !== '1' && t !== '2' && t !== '3'
          })
        }
      })
    }
  } catch {}
}

// 获取完整的危害数据（包含回退机制）
const getCompleteHazardData = (row: ExpandedTableItem) => {
  let hazard = row.hazard

  // 如果展开行中的危害数据不完整，尝试从原始数据中获取
  if (!hazard.mac && !hazard.pcTwa && !hazard.pcStel) {
    const position = findPositionByRow(row)
    if (position) {
      const originalRow = position.tableData.find((item) => item.id === row.originalId)
      if (originalRow && originalRow.hazards) {
        const originalHazard = originalRow.hazards.find((h) => h.id === hazard.id)
        if (originalHazard) {
          hazard = originalHazard
        }
      }
    }
  }

  return hazard
}

// 计算限值类型的默认值
const getDefaultStrengthType = (hazard: LocalHazard) => {
  if (!hazard || !hazard.sampling) return null

  const sampleType = hazard.sampling.sampleType
  const hazardType = parseInt(hazard.type) || 0 // 确保类型转换
  const hasMac = hazard.mac != null && hazard.mac !== '' && hazard.mac !== '—'
  const hasPcTwa = hazard.pcTwa != null && hazard.pcTwa !== '' && hazard.pcTwa !== '—'
  const hasPcStel = hazard.pcStel != null && hazard.pcStel !== '' && hazard.pcStel !== '—'
  let defaultValue = 1

  // 采样类型为 personal 时：type=1的时候，默认选中7，其他默认选中1
  if (sampleType === 'personal') {
    if (hazardType === 1) {
      return 7
    }
    if (hazardType === 2) {
      // 仅含 mac（无 pcTwa 和 pcStel）：限值类型固定为 value=3
      if (hasMac && !hasPcTwa && !hasPcStel) {
        return 7
      }
    }
  }
  // 采样类型为 fix 时：type=1时，默认选中7，type=2时，切mac不为空时候，默认选中7，其他情况默认都选择1
  else if (sampleType === 'fix') {
    if (hazardType === 1) {
      return 7
    }
    if (hazardType === 2) {
      // 仅含 mac（无 pcTwa 和 pcStel）：限值类型固定为 value=3
      if (hasMac && !hasPcTwa && !hasPcStel) {
        return 3
      }
    }
  }

  console.log(
    `[getDefaultStrengthType] 危害: ${hazard.cnName}, 原始类型: ${hazard.type}, 转换后类型: ${hazardType}, 采样类型: ${sampleType}, MAC: ${hazard.mac}, 默认限值类型: ${defaultValue}`
  )

  return defaultValue
}

// 计算采样时间类型的默认值
const getDefaultTimeType = (hazard: LocalHazard) => {
  const sampleType = hazard.sampling.sampleType
  const hazardType = parseInt(hazard.type) || 0 // 确保类型转换

  // 采样类型为 personal 且 type=1 时：timeType 默认选择 none
  const hasMac = hazard.mac != null && hazard.mac !== '' && hazard.mac !== '—'
  const hasPcTwa = hazard.pcTwa != null && hazard.pcTwa !== '' && hazard.pcTwa !== '—'
  const hasPcStel = hazard.pcStel != null && hazard.pcStel !== '' && hazard.pcStel !== '—'
  console.log(
    `sampleType{},hazardType{},hasMac{},hasPcTwa{},hasPcStel{}`,
    sampleType,
    hazardType,
    hasMac,
    hasPcTwa,
    hasPcStel
  )
  if (sampleType === 'fix') {
    if (hazardType === 1) {
      return 'none'
    }
    if (hazardType === 2) {
      console.log(`shortshortshort`)
      // 仅含 mac（无 pcTwa 和 pcStel）：限值类型固定为 value=3
      if (hasMac && !hasPcTwa && !hasPcStel) {
        return 'short'
      } else {
        return 'long'
      }
    }
    if (hazardType === 3) {
      return 'long'
    }
  } else {
    if (hazardType === 1) {
      return 'none'
    }
    if (hazardType === 2) {
      if (hasMac && !hasPcTwa && !hasPcStel) {
        return 'none'
      } else {
        return 'long'
      }
    }
    if (hazardType === 3) {
      return 'long'
    }
  }

  // 其他情况默认为 long
  console.log(`[getDefaultTimeType] 其他情况，采样时间类型为long`)
  return 'long'
}

// 过滤限值类型选项
const filterStrengthTypeOptions = (hazard: any) => {
  if (!hazard || !hazard.sampling) return strengthTypeOptions.value

  const sampleType = hazard.sampling.sampleType
  const hazardType = parseInt(hazard.type) || 0 // 确保类型转换
  const testStandardList = hazard.testStandardList || []
  const hasMac = hazard.mac != null && hazard.mac !== '' && hazard.mac !== '—'
  const hasPcTwa = hazard.pcTwa != null && hazard.pcTwa !== '' && hazard.pcTwa !== '—'
  const hasPcStel = hazard.pcStel != null && hazard.pcStel !== '' && hazard.pcStel !== '—'

  console.log(`[过滤限值类型] 危害: ${hazard.cnName}, 类型: ${hazardType}, 采样类型: ${sampleType}`)

  // 采样类型为 personal 时：限值类型固定为 value=1
  if (sampleType === 'personal') {
    return strengthTypeOptions.value.filter((option) => option.value === 1)
  }

  // 采样类型为 fix 时
  if (sampleType === 'fix') {
    if (hazardType === 1) {
      console.log('限值类型固定为 value=7')
      return strengthTypeOptions.value.filter((option) => option.value === 7)
    } else if (hazardType === 2) {
      if (hasMac && !hasPcTwa && !hasPcStel) {
        return strengthTypeOptions.value.filter((option) => option.value === 3)
      }
      if (!hasMac && hasPcTwa && !hasPcStel) {
        return strengthTypeOptions.value.filter((option) => [1, 4, 7].includes(option.value))
      }
      if (!hasMac && hasPcTwa && hasPcStel) {
        return strengthTypeOptions.value.filter((option) => [1, 2, 5, 7].includes(option.value))
      }
    } else {
      // 粉尘下拉
      return strengthTypeOptions.value.filter((option) => [1, 2, 5, 7].includes(option.value))
    }

    // 危害 type=1：限值类型固定选中 value=7
    // if (hazardType === 1) {
    //   return strengthTypeOptions.value.filter((option) => option.value === 7)
    // }
    //
    // // 危害 type=2：
    // if (hazardType === 2) {
    //   // 仅含 mac（无 pcTwa 和 pcStel）：限值类型固定为 value=3
    //   if (hasMac && !hasPcTwa && !hasPcStel) {
    //     return strengthTypeOptions.value.filter((option) => option.value === 3)
    //   }
    //
    //   // 仅含 pcTwa（无 mac 和 pcStel）：限值类型可选 1、4、6（默认选第一个）
    //   if (!hasMac && hasPcTwa && !hasPcStel) {
    //     return strengthTypeOptions.value.filter((option) => [1, 4, 6].includes(option.value))
    //   }
    //
    //   // 含 pcTwa 和 pcStel（无 mac）：限值类型可选 1、2、5（默认选第一个）
    //   if (!hasMac && hasPcTwa && hasPcStel) {
    //     return strengthTypeOptions.value.filter((option) => [1, 2, 5].includes(option.value))
    //   }
    // }
    //
    // // 危害 type=3：限值类型可选范围：value=1、4、6（默认选第一个）
    // if (hazardType === 3) {
    //   return strengthTypeOptions.value.filter((option) => [1, 4, 6].includes(option.value))
    // }
  }

  // 默认返回所有选项
  return strengthTypeOptions.value
}

// 添加默认工作时间的响应式变量
const workHours = ref<number>(0)
const defaultWorkHours = ref<number>(8)
const defaultWorkDays = ref<number>(5)
// 添加默认班制参数
const defaultShiftSystem = ref<string>('一班')

// 默认工作时段管理
const defaultWorkTimeSegments = ref<WorkTimeSegment[]>([])
const workTimeDialogVisible = ref(false)
const editingWorkTimeSegments = ref<WorkTimeSegment[]>([])
const editingShiftSystem = ref<string>('1')

// 布点维护
const pointMaintainDialogVisible = ref(false)
const pointMaintainRow = ref<any | null>(null)
const pointMaintainHazards = ref<any[]>([])
// 限值类型 1=PC-TWA 2=PC-STEL 3=PE
const pointMaintainStrengthTypes = ref<number[]>([1, 2, 4])
const pointMaintainHazardIds = ref<string[]>([])

// 岗位工作时段管理
const editingPosition = ref<any>(null) // 当前编辑的岗位
const isEditingPositionWorkTime = ref(false) // 是否在编辑岗位时段

// 格式化岗位工作时段显示
const formatPositionWorkTime = (position: any): string => {
  console.log(`[工作时段显示] 格式化岗位 "${position.name}" 的工作时段`)

  // 如果岗位有自定义工作时段数据，使用自定义数据
  if (position.workTimeSegments && position.workTimeSegments.length > 0) {
    const segments = position.workTimeSegments
      .map((segment: WorkTimeSegment) => `${segment.startTime}-${segment.endTime}`)
      .join(' || ')
    console.log(`[工作时段显示] 岗位 "${position.name}" 自定义时段: ${segments}`)
    return segments
  }

  // 如果有默认工作时段，使用默认时段
  if (defaultWorkTimeSegments.value.length > 0) {
    const segments = defaultWorkTimeSegments.value
      .map((segment) => `${segment.startTime}-${segment.endTime}`)
      .join(' || ')
    console.log(`[工作时段显示] 岗位 "${position.name}" 使用默认时段: ${segments}`)
    return segments
  }

  // 回退到原始的开始结束时间
  if (position.workStartTime && position.workEndTime) {
    const timeString = `${position.workStartTime}-${position.workEndTime}`
    console.log(`[工作时段显示] 岗位 "${position.name}" 使用原始时段: ${timeString}`)
    return timeString
  }

  console.log(`[工作时段显示] 岗位 "${position.name}" 无时段数据`)
  return '未设置'
}

// 打开岗位工作时段编辑弹窗
const openPositionWorkTimeDialog = (position: any) => {
  // console.log(`[岗位时段编辑] 打开岗位 `,JSON.stringify(position))

  editingPosition.value = position
  isEditingPositionWorkTime.value = true

  // 初始化编辑状态
  editingShiftSystem.value = position.shiftSystem || defaultShiftSystem.value

  // 如果岗位有自定义时段，使用自定义时段；否则使用默认时段
  if (position.workTimeSegments && position.workTimeSegments.length > 0) {
    editingWorkTimeSegments.value = JSON.parse(JSON.stringify(position.workTimeSegments))
    // console.log(`[岗位时段编辑] 使用岗位自定义时段，数量: ${editingWorkTimeSegments.value.length}`)
  } else {
    editingWorkTimeSegments.value = JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))
    // console.log(`[岗位时段编辑] 使用默认时段，数量: ${editingWorkTimeSegments.value.length}`)
  }

  // 如果没有时段，创建一个默认时段
  if (editingWorkTimeSegments.value.length === 0) {
    console.log(`[岗位时段编辑] 创建默认时段`)
    editingWorkTimeSegments.value = [createDefaultTimeSegment()]
  }
  workHours.value = position.workHours
  workTimeDialogVisible.value = true
  console.log(`[岗位时段编辑] 弹窗已打开，编辑时段数量: ${editingWorkTimeSegments.value.length}`)
}

// 处理默认工作天数变化
const handleDefaultWorkDaysChange = (value: number) => {
  console.log(`[默认参数变化] 工作天数: ${value}`)

  updateAllPositions((position) => {
    const oldDays = position.workDays
    position.workDays = value
    console.log(`[参数联动] 岗位 "${position.name}" 工作天数: ${oldDays} -> ${value}`)
  }, `已将所有岗位的工作天数更新为 ${value} 天`)
}

// 处理默认工作时间变化
const handleDefaultWorkHoursChange = (value: number) => {
  console.log(`[默认参数变化] 工作时间: ${value}`)

  // 更新所有岗位的工作时间
  tabList.value.forEach((workshop) => {
    console.log(`[默认参数联动] 更新车间 "${workshop.name}" 中的岗位工作时间`)
    workshop.positions?.forEach((position) => {
      const oldHours = position.workHours
      position.workHours = value

      // 同时更新岗位的工作地点接触时间
      // position.tableData?.forEach((tableRow) => {
      //   if (tableRow.workLocation === 1) {
      //     // 工作地点行
      //     const oldContactTime = tableRow.contactTime
      //     tableRow.contactTime = value
      //     console.log(
      //       `[默认参数联动] 岗位 "${position.name}" 工作地点 "${tableRow.testItem}" 接触时间: ${oldContactTime} -> ${value}`
      //     )
      //   } else if (tableRow.workLocation === 2) {
      //     // 劳动者行
      //     const oldContactTime = tableRow.contactTime
      //     tableRow.contactTime = value
      //     console.log(
      //       `[默认参数联动] 岗位 "${position.name}" 劳动者接触时间: ${oldContactTime} -> ${value}`
      //     )
      //   }
      // })

      console.log(`[默认参数联动] 岗位 "${position.name}" 工作时间: ${oldHours} -> ${value}`)
    })
  })

  // 更新弹窗中的岗位数据
  allPositions.value.forEach((position) => {
    const oldHours = position.workHours
    position.workHours = value

    // 同时更新弹窗中岗位的工作地点接触时间
    // position.workplaceData?.forEach((workplace) => {
    //   const oldContactTime = workplace.contactTime
    //   workplace.contactTime = value
    //   console.log(
    //     `[默认参数联动] 弹窗岗位 "${position.name}" 工作地点 "${workplace.workplace}" 接触时间: ${oldContactTime} -> ${value}`
    //   )
    // })

    console.log(`[默认参数联动] 弹窗岗位 "${position.name}" 工作时间: ${oldHours} -> ${value}`)
  })

  ElMessage.success(`已将所有岗位的工作时间更新为 ${value} 小时`)
}

// 处理默认班制变化
const handleDefaultShiftSystemChange = (value: string) => {
  console.log(`[默认参数变化] 班制: ${value}`)

  // 更新所有岗位的班制
  tabList.value.forEach((workshop) => {
    console.log(`[默认参数联动] 更新车间 "${workshop.name}" 中的岗位班制`)
    workshop.positions?.forEach((position) => {
      const oldShift = position.shiftSystem
      position.shiftSystem = value
      console.log(`[默认参数联动] 岗位 "${position.name}" 班制: ${oldShift} -> ${value}`)
    })
  })

  // 更新弹窗中的岗位数据
  allPositions.value.forEach((position) => {
    const oldShift = position.shiftSystem
    position.shiftSystem = value
    console.log(`[默认参数联动] 弹窗岗位 "${position.name}" 班制: ${oldShift} -> ${value}`)
  })

  const shiftLabel =
    getStrDictOptions(DICT_TYPE.SHIFT_DUTY).find((dict) => dict.value === value)?.label || value
  ElMessage.success(`已将所有岗位的班制更新为 ${shiftLabel}`)
}

// 打开工作时段设置弹窗
const openWorkTimeDialog = () => {
  console.log(`[工作时段弹窗] 打开工作时段设置弹窗`)
  workHours.value = defaultWorkHours.value
  // 初始化编辑状态
  editingShiftSystem.value = defaultShiftSystem.value
  editingWorkTimeSegments.value = JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))

  // 如果没有时段，创建一个默认时段
  if (editingWorkTimeSegments.value.length === 0) {
    console.log(`[工作时段弹窗] 创建默认时段`)
    editingWorkTimeSegments.value = [createDefaultTimeSegment()]
  }

  workTimeDialogVisible.value = true
  console.log(`[工作时段弹窗] 当前编辑时段数量: ${editingWorkTimeSegments.value.length}`)
}

// 创建默认时段
const createDefaultTimeSegment = (): WorkTimeSegment => {
  const id = `segment_${uuidv4()}`
  return {
    id,
    startTime: '09:00',
    endTime: '17:00',
    duration: 8
  }
}

// 添加时段
const addTimeSegment = () => {
  console.log(`[工作时段弹窗] 添加新时段`)
  const newSegment = createDefaultTimeSegment()
  editingWorkTimeSegments.value.push(newSegment)
  console.log(`[工作时段弹窗] 当前时段数量: ${editingWorkTimeSegments.value.length}`)
}

// 删除时段
const removeTimeSegment = (index: number) => {
  console.log(`[工作时段弹窗] 删除时段，索引: ${index}`)
  if (editingWorkTimeSegments.value.length <= 1) {
    ElMessage.warning('至少需要保留一个工作时段')
    return
  }
  editingWorkTimeSegments.value.splice(index, 1)
  console.log(`[工作时段弹窗] 删除后时段数量: ${editingWorkTimeSegments.value.length}`)
}

// 计算时段时长
const calculateSegmentDuration = (segment: WorkTimeSegment) => {
  if (!segment.startTime || !segment.endTime) {
    segment.duration = 0
    return
  }

  const [startHour, startMinute] = segment.startTime.split(':').map(Number)
  const [endHour, endMinute] = segment.endTime.split(':').map(Number)

  let startMinutes = startHour * 60 + startMinute
  let endMinutes = endHour * 60 + endMinute

  // 处理跨天的情况
  if (endMinutes <= startMinutes) {
    endMinutes += 24 * 60
  }

  const durationMinutes = endMinutes - startMinutes
  segment.duration = durationMinutes / 60

  console.log(
    `[工作时段弹窗] 计算时段时长: ${segment.startTime}-${segment.endTime} = ${segment.duration.toFixed(1)}小时`
  )
}

// 获取总时长
const getTotalDuration = (): number => {
  const total = editingWorkTimeSegments.value.reduce((sum, segment) => sum + segment.duration, 0)
  return Math.round(total * 10) / 10 // 保留一位小数
}

// 处理编辑中的班制变化
const handleEditingShiftSystemChange = (value: string) => {
  console.log(`[工作时段弹窗] 班制变化: ${value}`)
  editingShiftSystem.value = value

  // 根据班制调整默认时段数量
  const shiftLabel =
    getStrDictOptions(DICT_TYPE.SHIFT_DUTY).find((dict) => dict.value === value)?.label || value
  console.log(`[工作时段弹窗] 班制名称: ${shiftLabel}`)

  // 可以根据班制类型自动调整时段（如两班倒、三班倒等）
  if (shiftLabel.includes('两班') || shiftLabel.includes('2班')) {
    console.log(`[工作时段弹窗] 检测到两班倒，建议设置2个时段`)
  } else if (shiftLabel.includes('三班') || shiftLabel.includes('3班')) {
    console.log(`[工作时段弹窗] 检测到三班倒，建议设置3个时段`)
  }
}

// 确认工作时段设置
const confirmWorkTimeDialog = () => {
  console.log(
    `[工作时段弹窗] 确认时段设置，编辑模式: ${isEditingPositionWorkTime.value ? '岗位' : '默认'}`
  )

  // 验证总时长
  const totalDuration = getTotalDuration()
  if (Math.abs(totalDuration - defaultWorkHours.value) > 0.1) {
    ElMessage.error(`总时长(${totalDuration}小时)与工作时间(${defaultWorkHours.value}小时)不一致`)
    return
  }

  // 验证每个时段都有完整的时间设置
  const invalidSegments = editingWorkTimeSegments.value.filter(
    (segment) => !segment.startTime || !segment.endTime
  )
  if (invalidSegments.length > 0) {
    ElMessage.error('请完善所有时段的开始和结束时间')
    return
  }

  if (isEditingPositionWorkTime.value && editingPosition.value) {
    // 岗位专用时段编辑
    console.log(`[岗位时段编辑] 保存岗位 "${editingPosition.value.name}" 的时段设置`)

    // 保存岗位的班制和时段数据
    editingPosition.value.shiftSystem = editingShiftSystem.value
    editingPosition.value.workTimeSegments = JSON.parse(
      JSON.stringify(editingWorkTimeSegments.value)
    )

    // 更新岗位的开始结束时间（兼容性）
    if (editingWorkTimeSegments.value.length > 0) {
      const firstSegment = editingWorkTimeSegments.value[0]
      const lastSegment = editingWorkTimeSegments.value[editingWorkTimeSegments.value.length - 1]
      editingPosition.value.workStartTime = firstSegment.startTime
      editingPosition.value.workEndTime = lastSegment.endTime
    }

    console.log(
      `[岗位时段编辑] 岗位 "${editingPosition.value.name}" 班制: ${editingPosition.value.shiftSystem}`
    )
    console.log(
      `[岗位时段编辑] 岗位 "${editingPosition.value.name}" 时段:`,
      editingPosition.value.workTimeSegments
    )
    console.log(
      `[岗位时段编辑] 岗位 "${editingPosition.value.name}" 时段范围: ${editingPosition.value.workStartTime}-${editingPosition.value.workEndTime}`
    )

    ElMessage.success(`岗位 "${editingPosition.value.name}" 的工作时段设置已保存`)

    // 跨车间同步：相同岗位名的班制与工作时段
    try {
      console.log(
        `[跨车间同步][工作时段] 开始同步岗位 "${editingPosition.value.name}" 的班制与时段`
      )
      const name = editingPosition.value.name
      const segs = JSON.parse(JSON.stringify(editingWorkTimeSegments.value))
      const start = editingPosition.value.workStartTime
      const end = editingPosition.value.workEndTime
      const shift = editingShiftSystem.value
      tabList.value.forEach((workshop) => {
        workshop.positions?.forEach((pos) => {
          if (pos !== editingPosition.value && !pos?.isDeleted && pos?.name === name) {
            const oldShift = pos.shiftSystem
            const oldStart = pos.workStartTime
            const oldEnd = pos.workEndTime
            pos.shiftSystem = shift
            pos.workTimeSegments = JSON.parse(JSON.stringify(segs))
            pos.workStartTime = start
            pos.workEndTime = end
            console.log(
              `[跨车间同步][工作时段] 车间 "${workshop.name}" 岗位 "${name}" 班制: ${oldShift} -> ${shift}`
            )
            console.log(
              `[跨车间同步][工作时段] 车间 "${workshop.name}" 岗位 "${name}" 时段: ${oldStart}-${oldEnd} -> ${start}-${end}`
            )
          }
        })
      })
    } catch (e) {
      console.log('[跨车间同步][工作时段] 同步失败:', e)
    }

    // 清除编辑状态
    editingPosition.value = null
    isEditingPositionWorkTime.value = false
  } else {
    // 默认时段编辑
    console.log(`[工作时段弹窗] 保存默认时段设置`)

    // 保存设置
    defaultShiftSystem.value = editingShiftSystem.value
    defaultWorkTimeSegments.value = JSON.parse(JSON.stringify(editingWorkTimeSegments.value))

    console.log(`[工作时段弹窗] 保存班制: ${defaultShiftSystem.value}`)
    console.log(`[工作时段弹窗] 保存时段:`, defaultWorkTimeSegments.value)

    // 联动更新所有岗位
    updateAllPositionsWorkTime()

    ElMessage.success('默认工作时段设置已保存并同步到所有岗位')
  }

  workTimeDialogVisible.value = false
}

// 取消工作时段设置
const cancelWorkTimeDialog = () => {
  console.log(
    `[工作时段弹窗] 取消时段设置，编辑模式: ${isEditingPositionWorkTime.value ? '岗位' : '默认'}`
  )

  // 清除编辑状态
  if (isEditingPositionWorkTime.value) {
    editingPosition.value = null
    isEditingPositionWorkTime.value = false
  }

  workTimeDialogVisible.value = false
}

// 统一的岗位更新函数 - 简化联动逻辑
const updateAllPositions = (updateFn: (position: any) => void, successMessage?: string) => {
  console.log(`[统一联动] 开始更新所有岗位`)

  // 更新车间中的岗位
  tabList.value.forEach((workshop) => {
    workshop.positions?.forEach((position) => updateFn(position))
  })

  // 更新弹窗中的岗位
  allPositions.value.forEach((position) => updateFn(position))

  if (successMessage) {
    ElMessage.success(successMessage)
  }

  console.log(`[统一联动] 所有岗位更新完成`)
}

// 更新所有岗位的工作时段
const updateAllPositionsWorkTime = () => {
  console.log(`[工作时段联动] 开始更新所有岗位的工作时段`)

  // 更新车间中的岗位
  tabList.value.forEach((workshop) => {
    workshop.positions?.forEach((position) => {
      const oldShift = position.shiftSystem
      const oldStartTime = position.workStartTime
      const oldEndTime = position.workEndTime

      position.shiftSystem = defaultShiftSystem.value

      if (defaultWorkTimeSegments.value.length > 0) {
        const firstSegment = defaultWorkTimeSegments.value[0]
        const lastSegment = defaultWorkTimeSegments.value[defaultWorkTimeSegments.value.length - 1]
        position.workStartTime = firstSegment.startTime
        position.workEndTime = lastSegment.endTime

        // 强制同步默认工作时段到所有岗位（移除条件判断）
        position.workTimeSegments = JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))
        console.log(
          `[工作时段联动] 岗位 "${position.name}" 同步默认时段:`,
          position.workTimeSegments
        )
      }

      console.log(
        `[工作时段联动] 岗位 "${position.name}" 班制: ${oldShift} -> ${position.shiftSystem}`
      )
      console.log(
        `[工作时段联动] 岗位 "${position.name}" 时段: ${oldStartTime}-${oldEndTime} -> ${position.workStartTime}-${position.workEndTime}`
      )
    })
  })

  // 更新弹窗中的岗位
  allPositions.value.forEach((position) => {
    const oldShift = position.shiftSystem
    const oldStartTime = position.workStartTime
    const oldEndTime = position.workEndTime

    position.shiftSystem = defaultShiftSystem.value

    if (defaultWorkTimeSegments.value.length > 0) {
      const firstSegment = defaultWorkTimeSegments.value[0]
      const lastSegment = defaultWorkTimeSegments.value[defaultWorkTimeSegments.value.length - 1]
      position.workStartTime = firstSegment.startTime
      position.workEndTime = lastSegment.endTime

      // 强制同步默认工作时段到所有岗位（移除条件判断）
      position.workTimeSegments = JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))
      console.log(
        `[工作时段联动] 弹窗岗位 "${position.name}" 同步默认时段:`,
        position.workTimeSegments
      )
    }

    console.log(
      `[工作时段联动] 弹窗岗位 "${position.name}" 班制: ${oldShift} -> ${position.shiftSystem}`
    )
    console.log(
      `[工作时段联动] 弹窗岗位 "${position.name}" 时段: ${oldStartTime}-${oldEndTime} -> ${position.workStartTime}-${position.workEndTime}`
    )
  })

  console.log(`[工作时段联动] 所有岗位工作时段更新完成`)
}
const handleNumberInput = (value: number, field: string, position?: any) => {
  if (isNaN(value)) return

  if (position) {
    if (field === 'workHours' || field === 'workDays') {
      position[field] = value // 现在使用数字类型
    } else {
      position[field] = value
    }
    if (field === 'shiftCount') {
      calculateTotalPeople(position)
    }
    // 跨车间同步：相同岗位名的基础数值字段
    try {
      const name = position.name
      tabList.value.forEach((workshop) => {
        workshop.positions?.forEach((pos) => {
          if (pos !== position && !pos?.isDeleted && pos?.name === name) {
            const oldVal = (pos as any)[field]
            ;(pos as any)[field] = value
            if (field === 'shiftCount') {
              calculateTotalPeople(pos)
            }
            console.log(
              `[跨车间同步][基础信息] 车间 "${workshop.name}" 岗位 "${name}" 字段 ${field}: ${oldVal} -> ${value}`
            )

            // 工作时间/天数联动更新接触时间
            if (field === 'workHours' || field === 'workDays') {
              handleWorkTimeChange(pos)
            }
          }
        })
      })
    } catch (e) {
      console.log('[跨车间同步][基础信息] 同步失败:', e)
    }
  } else {
    if (field === 'workHours') {
      defaultWorkHours.value = value
    } else if (field === 'workDays') {
      defaultWorkDays.value = value
    }
  }
}

// 修改监听默认值变化的逻辑
watch([defaultWorkHours, defaultWorkDays], ([newHours, newDays]) => {
  tabList.value.forEach((tab) => {
    tab.positions?.forEach((position) => {
      // 只更新未手动修改过的岗位
      if (!position.isCustomWorkTime) {
        position.workHours = newHours
        position.workDays = newDays

        // 更新表格中的接触时间
        // position.tableData.forEach((row) => {
        //   // 检查行是否有自定义的接触时间
        //   const hazardHasCustomTime = row.hazards?.some((hazard) => hazard.sampling?.isCustomTime)
        //
        //   // 如果没有自定义时间，则更新接触时间
        //   if (!hazardHasCustomTime) {
        //     row.contactTime = newHours
        //
        //     // 同时更新每个危害的采样接触时间
        //     if (row.hazards) {
        //       row.hazards.forEach((hazard) => {
        //         if (hazard.sampling && !hazard.sampling.isCustomTime) {
        //           hazard.sampling.contactHours = parseFloat(newHours)
        //         }
        //       })
        //     }
        //   }
        // })
      }
    })
  })
})

// 修改 handleWorkTimeChange 函数
const handleWorkTimeChange = (position: PositionBlock) => {
  position.isCustomWorkTime = true

  // 更新该岗位下所有行的接触时间
  const updatedTableData = position.tableData.map((row) => {
    const updatedRow = { ...row }
    if (!updatedRow.hazards?.some((hazard) => hazard.sampling?.isCustomTime)) {
      updatedRow.contactTime = position.workHours

      // 同时更新危害的采样接触时间
      if (updatedRow.hazards) {
        updatedRow.hazards = updatedRow.hazards.map((hazard) => {
          const updatedHazard = { ...hazard }
          if (updatedHazard.sampling && !updatedHazard.sampling.isCustomTime) {
            updatedHazard.contactTime = position.workHours
            if (updatedHazard.sampling) {
              updatedHazard.sampling.contactHours = Number(position.workHours)
            }
          }
          return updatedHazard
        })
      }
    }
    return updatedRow
  })

  // 更新表格数据
  position.tableData = updatedTableData
}

// 修改：生成唯一的行ID
const generateUniqueId = (prefix: string, positionId: string, index: number) => {
  return `${prefix}_${positionId}_${index}`
}

// 修改 generateMockData 函数，添加接触频度相关数据
const generateMockData = (
  prefix: string,
  positionId: string,
  positionName: string,
  workLocations?: WorkLocation[]
): TableItem[] => {
  const tableData: TableItem[] = []

  // 处理岗位名称的拼接逻辑
  const getSuffix = (name: string) => {
    if (name.endsWith('岗位')) {
      return '' // 如果以"岗位"结尾，不添加任何后缀
    } else if (name.endsWith('工')) {
      return '位' // 如果以"工"结尾，添加"位"
    } else {
      return '工位' // 其他情况添加"工位"
    }
  }

  // 1. 先添加工作地点（工位）记录
  //    注意：按需求将劳动者行（workLocation: 2）放在集合队尾，故先生成工位行

  // 2. 如果是流动岗位且有工位信息，则为每个工位添加记录
  if (workLocations && workLocations.length > 0) {
    workLocations.forEach((location, index) => {
      // 获取对应车间的名称
      const locationWorkshopId = location.workshopId || location.workshop || ''
      const workshopName = tabList.value.find((tab) => tab.id === locationWorkshopId)?.name || ''
      const locationName = location.locationName || location.workInfo
      const locationSuffix = getSuffix(locationName)

      tableData.push({
        id: generateUniqueId(prefix, positionId, index + 1),
        rowKey: `${prefix}_${positionId}_${index + 1}_${uuidv4()}`,
        testItem: `${positionName}${getSuffix(positionName)}`,
        workLocation: 1,
        contactTime: defaultWorkHours.value,
        workContent: '',
        laborIntensity: '',
        source: '',
        // 添加接触频度数据
        contactFrequency: {
          count: 1,
          duration: 1,
          interval: 1
        },
        fluctuationTime: '',
        remark: '',
        hazards: [],
        personalProtection: '',
        personalProtectionList: [],
        personalProtectionIds: [],
        protectiveFacilities: '',
        protectiveFacilitiesList: [],
        protectiveFacilitiesIds: [],
        sampleMethod: undefined,
        longShortTime: undefined,
        sampleDuration: undefined,
        flowRate: undefined,
        strengthType: undefined,
        sampleDays: undefined,
        sampleCount: undefined,
        backupCount: undefined,
        sampleCode: '',
        isFirstHazard: true,
        hazardCount: 1,
        originalId: generateUniqueId(prefix, positionId, index + 1)
      })
    })
  } else {
    // 3. 默认添加一条工位记录
    const defaultSuffix = getSuffix(positionName)
    tableData.push({
      id: generateUniqueId(prefix, positionId, 1),
      rowKey: `${prefix}_${positionId}_1_${uuidv4()}`,
      testItem: `${positionName}${defaultSuffix}`,
      workLocation: 1,
      contactTime: defaultWorkHours.value,
      workContent: '',
      laborIntensity: '',
      source: '',
      // 添加接触频度数据
      contactFrequency: {
        count: 1,
        duration: 1,
        interval: 1
      },
      fluctuationTime: '',
      remark: '',
      hazards: [],
      personalProtection: '',
      personalProtectionList: [],
      personalProtectionIds: [],
      protectiveFacilities: '',
      protectiveFacilitiesList: [],
      protectiveFacilitiesIds: [],
      sampleMethod: undefined,
      longShortTime: undefined,
      sampleDuration: undefined,
      flowRate: undefined,
      strengthType: undefined,
      sampleDays: undefined,
      sampleCount: undefined,
      backupCount: undefined,
      sampleCode: '',
      isFirstHazard: true,
      hazardCount: 1,
      originalId: generateUniqueId(prefix, positionId, 1)
    })
  }

  // 4. 最后添加“劳动者”记录，放在队尾（workLocation 设为 2）
  tableData.push({
    id: generateUniqueId(prefix, positionId, 0),
    rowKey: `${prefix}_${positionId}_0_${uuidv4()}`,
    testItem: '劳动者',
    contactTime: defaultWorkHours.value,
    workContent: '',
    laborIntensity: '',
    source: '',
    // 添加接触频度数据
    contactFrequency: {
      count: 1,
      duration: 1,
      interval: 1
    },
    workLocation: 2,
    fluctuationTime: '',
    remark: '',
    hazards: [],
    personalProtection: '',
    personalProtectionList: [],
    personalProtectionIds: [],
    protectiveFacilities: '',
    protectiveFacilitiesList: [],
    protectiveFacilitiesIds: [],
    sampleMethod: undefined,
    longShortTime: undefined,
    sampleDuration: undefined,
    flowRate: undefined,
    strengthType: undefined,
    sampleDays: undefined,
    sampleCount: undefined,
    backupCount: undefined,
    sampleCode: '',
    isFirstHazard: true,
    hazardCount: 1,
    originalId: generateUniqueId(prefix, positionId, 0)
  })

  return tableData
}

// 生成唯一ID
const generateId = () => {
  const id = 'tab_' + uuidv4()
  console.log('generateId', id)
  return id
}

// 修改 generateEmptyPosition 函数
const generateEmptyPosition = (prefix: string, index: number, name: string = ''): PositionBlock => {
  const positionId = `position_${uuidv4()}` // 生成唯一的岗位ID
  const positionName = name || `岗位${index + 1}` // 使用传入的名称或默认名称
  return {
    id: positionId,
    name: positionName, // 添加name属性
    tableData: generateMockData(prefix, positionId, positionName),
    totalPeople: 1,
    shiftCount: 1,
    shiftSystem: '一班',
    workMode: '',
    workPosition: '',
    workHours: defaultWorkHours.value,
    workDays: defaultWorkDays.value,
    workStartTime:
      defaultWorkTimeSegments.value.length > 0
        ? defaultWorkTimeSegments.value[0].startTime
        : '09:00',
    workEndTime:
      defaultWorkTimeSegments.value.length > 0
        ? defaultWorkTimeSegments.value[defaultWorkTimeSegments.value.length - 1].endTime
        : '17:00',
    workTimeSegments:
      defaultWorkTimeSegments.value.length > 0
        ? JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))
        : [
          {
            id: `segment_${uuidv4()}`,
            startTime: '09:00',
            endTime: '17:00',
            duration: 8
          }
        ],
    isCustomWorkTime: false
  }
}

// 添加新Tab
const handleAddTab = () => {
  // 打开弹窗，watch会自动初始化workshopList
  workshopDialogVisible.value = true
}

// 删除Tab
const removeTab = async (targetName: string) => {
  try {
    // 找到要删除的车间
    const tabToDelete = tabList.value.find((tab) => tab.id === targetName)
    if (!tabToDelete) {
      console.error('未找到要删除的车间')
      return
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
      `确认删除${tabToDelete.name}吗？删除后该车间下的所有数据将清空`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 获取当前激活的车间
    const currentActiveTab = activeTab.value

    // 如果删除的是当前激活的车间，需要设置新的激活车间
    if (currentActiveTab === targetName) {
      // 找到剩余车间中的第一个作为新的激活车间
      const remainingTabs = tabList.value.filter((tab) => tab.id !== targetName)
      if (remainingTabs.length > 0) {
        activeTab.value = remainingTabs[0].id
      } else {
        activeTab.value = ''
      }
    }

    // 更新车间列表，移除要删除的车间
    const updatedTabs = tabList.value.filter((tab) => tab.id !== targetName)

    // 更新 store 中的数据
    surveyStore.updateTabList(updatedTabs)
    surveyStore.updateActiveTab(activeTab.value)

    ElMessage.success(`${tabToDelete.name}已删除`)
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除，不做任何操作
      console.log('用户取消删除车间')
    } else {
      ElMessage.error('删除车间失败')
    }
  }
}

// 编辑Tab名称
const handleEditTab = (tab: TabItem) => {
  editingWorkshop.value = tab
  editingWorkshopName.value = tab.name
  editWorkshopDialogVisible.value = true
}

// 复制车间
const handleCopyTab = (tab: TabItem) => {
  // 深拷贝车间数据
  const newTab = JSON.parse(JSON.stringify(tab))

  // 生成新的车间ID
  newTab.id = generateId()

  // 生成新的车间名称，避免重名
  let baseName = tab.name.replace(/(\(复制\d*\))?$/, '')
  let copyIndex = 1
  let newName = `${baseName}(复制)`
  const existNames = tabList.value.map((t) => t.name)
  while (existNames.includes(newName)) {
    copyIndex++
    newName = `${baseName}(复制${copyIndex})`
  }
  newTab.name = newName
  newTab.isEditing = false
  newTab.editingName = newName

  // 为所有岗位和表格数据生成新的ID
  if (newTab.positions) {
    newTab.positions = newTab.positions.map((position) => {
      const newPosition = { ...position }
      newPosition.id = `position_${uuidv4()}`

      // 为表格数据生成新的ID
      if (newPosition.tableData) {
        newPosition.tableData = newPosition.tableData.map((row) => ({
          ...row,
          id: `${row.id}_copy_${uuidv4()}`,
          rowKey: `${row.rowKey}_copy_${uuidv4()}`
        }))
      }

      return newPosition
    })
  }

  // 添加到车间列表
  const updatedTabs = [...tabList.value, newTab]
  surveyStore.updateTabList(updatedTabs)

  // 切换到新复制的车间
  surveyStore.updateActiveTab(newTab.id)

  ElMessage.success('车间复制成功')
}

// 保存Tab名称
const handleSaveTabName = (tab: TabItem) => {
  if (!tab.editingName.trim()) {
    ElMessage.warning('车间名称不能为空')
    tab.editingName = tab.name // 恢复原名称
    tab.isEditing = false
    return
  }

  const isDuplicate = tabList.value.some(
    (item) => item.id !== tab.id && item.name === tab.editingName.trim()
  )

  if (isDuplicate) {
    ElMessage.warning('车间名称已存在')
    tab.editingName = tab.name // 恢复原名称
    tab.isEditing = false
    return
  }

  tab.name = tab.editingName.trim()
  tab.isEditing = false
}


// 修改：处理关闭危害识别弹窗
const handleHazardDialogClose = () => {
  console.log('=== 危害识别弹窗关闭 ===')
  // 强制刷新表格数据
  currentRow.value = null
}

// 添加刷新所有表格的方法
const refreshAllTables = () => {
  console.log('=== 刷新所有表格 ===')

  // 刷新所有车间的数据，不仅仅是当前车间
  tabList.value.forEach((tab) => {
    if (tab.positions && tab.positions.length > 0) {
      console.log(`=== 刷新车间 "${tab.name}" 的表格数据 ===`)
      // 创建当前tab的positions副本并重新赋值，触发Vue的响应式更新
      tab.positions = [
        ...tab.positions.map((position) => ({
          ...position,
          tableData: [...position.tableData]
        }))
      ]
      console.log(`=== 车间 "${tab.name}" 表格刷新完成，岗位数量: ${tab.positions.length} ===`)
    }
  })

  console.log('=== 所有表格刷新完成 ===')
}

// 修改：处理表格数据，展开危害列表
// 方案模式下用于合并“测量号”的 span 方法
const handleSpanMethod2 = ({ row, column, rowIndex, columnIndex }) => {
  // 调查模式下且为固定工位，不合并
  if (props.operationType === 1 && row.workLocation === 1) {
    return { rowspan: 1, colspan: 1 }
  }

  // 方案模式下：测量号列（按工位/采样点分组，与 testItem 一致）
  if (props.operationType === 2 && column?.property === 'measurementNo') {
    if (row.isFirstHazard) {
      return { rowspan: row.hazardCount, colspan: 1 }
    }
    return { rowspan: 0, colspan: 0 }
  }

  // 检测项目/采样对象列：按危害合并
  if (column?.property === 'testItem') {
    if (row.isFirstHazard) {
      return { rowspan: row.hazardCount, colspan: 1 }
    }
    return { rowspan: 0, colspan: 0 }
  }

  // 操作列等固定列：仍按危害合并
  if (column.type === 'operation' || column.fixed === 'right') {
    if (row.isFirstHazard) {
      return { rowspan: row.hazardCount, colspan: 1 }
    }
    return { rowspan: 0, colspan: 0 }
  }

  // 其他列不合并
  return { rowspan: 1, colspan: 1 }
}

const getExpandedTableData = (tableData: TableItem[]) => {
  console.log('=== getExpandedTableData 开始 ===')
  console.log('当前 operationType:', props.operationType)
  const filteredHazards: Hazard[] = []
  for (let tableDatum of tableData) {
    const hazards = tableDatum.hazards
    console.log(`处理表格行: ${tableDatum.testItem}, 危害数量: ${hazards?.length || 0}`)
    for (let hazard of hazards) {
      // 逻辑删除：按页面过滤
      if (
        (props.operationType === 2 && (hazard as any)?.deletedInPage2) ||
        (props.operationType === 1 && (hazard as any)?.deletedInPage1)
      )
        continue
      // 数据源 1是现场调查 2方案
      const pageNo = hazard.operationType
      const mac = hazard.mac
      const type = hazard.type
      const pcTwa = hazard.pcTwa
      const pcStel = hazard.pcStel
      // 当前查看的页面
      const operationType = props.operationType

      console.log(`处理危害: ${hazard.cnName}, pageNo=${pageNo}, operationType=${operationType}`)
      // 有限值 只有化学因素才要关注是否有限制 和检测标准
      const hasMacPcTwaPcStel =
        (mac != null && mac !== '' && mac !== '—') ||
        (pcTwa != null && pcTwa !== '' && pcTwa !== '—') ||
        (pcStel != null && pcStel !== '' && mac !== '—') ||
        parseInt(type + '') !== 2
      const hasTestStandard =
        hazard.testStandard != null && hazard.testStandard !== '' && hazard.testStandard !== '—'
      // 有检测标准
      const hit = hasMacPcTwaPcStel && hasTestStandard
      // 打开的是调查页面
      if (operationType == 1) {
        if (pageNo === 1) {
          console.log(`添加危害到过滤列表: ${hazard.cnName} (pageNo=${pageNo})`)
          filteredHazards.push(hazard)
        }
        if (pageNo === 2 && hit) {
          filteredHazards.push(hazard)
        }
      }
      // 打开的是方案页面
      if (operationType == 2) {
        {
          if (pageNo === 1 && hit) {
            filteredHazards.push(hazard)
          }

          if (pageNo === 2) {
            filteredHazards.push(hazard)
          }
        }
      }
    }
  }

  // 获取所有过滤后的危害名称
  const cnNames = filteredHazards.map((item) => item.cnName)
  // 去重
  const allowedCnNames = [...new Set(cnNames)]
  console.log('=== 过滤结果 ===')
  console.log('filteredHazards 数量:', filteredHazards.length)
  console.log(
    'filteredHazards 详情:',
    JSON.stringify(
      filteredHazards.map((h) => ({
        cnName: h.cnName,
        operationType: h.operationType
      }))
    )
  )
  console.log('allowedCnNames:', JSON.stringify(allowedCnNames))
  // 原来记录过滤出允许的，得到新的tableData
  if (allowedCnNames.length > 0) {
    tableData = tableData.map((item) => ({
      ...item,
      hazards: (item.hazards || []).filter(
        (hazard: any) =>
          allowedCnNames.includes(hazard.cnName) &&
          (props.operationType !== 2 || !hazard?.deletedInPage2)
      )
    }))
    // 注意：不要过滤掉没有危害的行，因为工作地点行也需要显示
    // .filter((item) => item.hazards.length > 0) // 移除这行过滤
  }

  const expandedData: ExpandedTableItem[] = []

  // 如果是开料工且workLocation=1，需要合并显示
  if (props.operationType === 1) {
    // 按workLocation+testItem+id分组，确保不同testItem和id不会被合并
    const groupedData = tableData.reduce(
      (acc, row) => {
        // 分组key包含workLocation、testItem、id，防止不同testItem、id被合并
        const key = `${row.workLocation}__${row.testItem || ''}__${row.id}`
        if (!acc[key]) {
          acc[key] = []
        }
        acc[key].push(row)
        return acc
      },
      {} as Record<string, TableItem[]>
    )

    // 处理每个分组
    Object.entries(groupedData).forEach(([groupKey, rows]) => {
      const location = Number(rows[0].workLocation)
      if (true) {
        // workLocation=1的组，合并显示
        const allHazards: Hazard[] = rows.reduce<Hazard[]>((acc, row) => {
          const hazardsAll = row.hazards || []
          return acc.concat(hazardsAll)
        }, [])

        if (allHazards.length > 0) {
          // 使用第一行的基础数据
          const baseRow = rows[0]
          // 合并所有危害的名称（按名称去重）
          const hazardNames = getUniqueHazardsByName(allHazards as any[])
            .map((h: any) => h.cnName)
            .join('、')
          // 获取第一行的工作内容
          const workContent = baseRow.hazards?.[0]?.workContent || ''
          // 构建来源文本：始终根据当前testItem重新生成，确保与工位名称同步
          let sourceText = ''
          if (baseRow.testItem) {
            // 去掉工作地点最后的"工位"2字，然后进行拼接
            const sourceValue = baseRow.testItem.replace(/工位$/, '')
            sourceText = `${sourceValue}时产生${hazardNames}`
          } else if (baseRow.source) {
            sourceText = baseRow.source
          }

          expandedData.push({
            ...baseRow,
            hazard: {
              ...allHazards[0], // 保留完整的危害信息，包括 mac、pcTwa、pcStel、testStandardList 等
              cnName: hazardNames,
              workContent: workContent,
              source: sourceText,
              laborIntensity: allHazards[0]?.laborIntensity
            },
            isFirstHazard: true,
            hazardCount: 1,
            originalId: baseRow.id,
            rowKey: baseRow.rowKey,
            contactTime: baseRow.contactTime,
            contactFrequency: baseRow.contactFrequency || { count: 1, duration: 1, interval: 1 },
            workLocation: baseRow.workLocation
          })
          // 如果存在已保存的来源，则覆盖默认生成的来源文本，避免用户修改被还原
          if (baseRow.source && expandedData.length > 0) {
            const last = expandedData[expandedData.length - 1]
            if (last && last.hazard) {
              last.hazard.source = baseRow.source
            }
          }
        } else {
          // 如果没有危害，显示一行空数据
          const baseRow = rows[0]
          expandedData.push({
            ...baseRow,
            hazard: undefined,
            isFirstHazard: true,
            hazardCount: 1,
            originalId: baseRow.id,
            rowKey: baseRow.rowKey,
            workLocation: baseRow.workLocation
          })
        }
      }
    })
  } else {
    // operationType=2 直接使用原表数据
    // 实时计算劳动者行的接触时间（workLocation=2）
    const hazardContactTimeMap = new Map<string, number>()
    tableData.forEach((row) => {
      if (row.workLocation === 1 && row.hazards?.length > 0) {
        // 方案模式汇总劳动者接触时间时，忽略逻辑删除的 hazard（只看 deletedInPage2）
        const hazardsForCalc = (row.hazards || []).filter((h: any) => !h?.deletedInPage2)
        // 去重：同一工作地点行内按危害名称去重（取同名的最大接触时间），避免重复计入
        const perNameMax = new Map<string, number>()
        hazardsForCalc.forEach((hazard) => {
          const name = hazard.cnName
          const contactTime = parseFloat(hazard.contactTime || row.contactTime || '0')
          const prev = perNameMax.get(name) || 0
          if (contactTime > prev) perNameMax.set(name, contactTime)
        })
        // 按名称汇总到总表
        perNameMax.forEach((time, name) => {
          const current = hazardContactTimeMap.get(name) || 0
          hazardContactTimeMap.set(name, current + time)
        })
      }
    })

    // 原有的展开逻辑
    tableData.forEach((row) => {
      if (!row.hazards || row.hazards.length === 0) {
        expandedData.push({
          ...row,
          hazard: undefined,
          isFirstHazard: true,
          hazardCount: 1,
          originalId: row.id,
          rowKey: row.rowKey,
          contactTime: row.contactTime,
          contactFrequency: row.contactFrequency || { count: 1, duration: 1, interval: 1 }
        })
      } else {
        // 方案模式隐藏逻辑删除的hazard（deletedInPage2）；调查页保留显示
        const filteredHazards =
          props.operationType === 2
            ? (row.hazards || []).filter((h: any) => !h?.deletedInPage2)
            : row.hazards

        if (filteredHazards.length === 0) {
          // 如果过滤后没有危害，显示空行
          expandedData.push({
            ...row,
            hazard: undefined,
            isFirstHazard: true,
            hazardCount: 1,
            originalId: row.id,
            rowKey: row.rowKey,
            contactTime: row.contactTime,
            contactFrequency: row.contactFrequency || { count: 1, duration: 1, interval: 1 }
          })
        } else {
          filteredHazards.forEach((hazard, index) => {
            const hazardRowKey = `${row.rowKey || row.id}_hazard_${hazard.id}_${index}`
            let sourceText = ''
            if (row.testItem) {
              // 去掉工作地点最后的"工位"2字，然后进行拼接
              const sourceValue = row.testItem.replace(/工位$/, '')
              sourceText = `${sourceValue}时产生${hazard.cnName}`
            } else if (row.source) {
              sourceText = row.source
            } else {
              sourceText = hazard.source || ''
            }

            // 劳动者行使用实时计算的接触时间
            const calculatedContactTime =
              row.workLocation === 2
                ? (hazardContactTimeMap.get(hazard.cnName) || 0).toString()
                : hazard.contactTime || row.contactTime

            expandedData.push({
              ...row,
              hazard: {
                ...hazard,
                workContent: hazard.workContent || '',
                source: sourceText,
                laborIntensity: hazard.laborIntensity,
                contactFrequency: hazard.contactFrequency ||
                  row.contactFrequency || {
                    count: 1,
                    duration: 1,
                    interval: 1
                  }
              },
              isFirstHazard: index === 0,
              hazardCount: filteredHazards.length,
              originalId: row.id,
              id: index === 0 ? row.id : `${row.id}_hazard_${hazard.id}_${index}`,
              rowKey: hazardRowKey,
              contactTime: calculatedContactTime,
              contactFrequency: hazard.contactFrequency ||
                row.contactFrequency || { count: 1, duration: 1, interval: 1 }
            })
            // 如果存在已保存的来源（行级或危害级），则覆盖默认生成的来源文本
            if ((row.source || hazard.source) && expandedData.length > 0) {
              const last = expandedData[expandedData.length - 1]
              if (last && last.hazard) {
                last.hazard.source = row.source || hazard.source || last.hazard.source
              }
            }
          })
        }
      }
    })
  }
  // 标记工位级的合并信息（仅方案模式使用）
  if (props.operationType === 2) {
    const total = expandedData.length
    expandedData.forEach((r, idx) => {
      r.isFirstPositionRow = idx === 0
      r.positionRowSpan = total
    })
  }
  // 标记工位级的合并信息（仅方案模式使用）
  if (props.operationType === 2) {
    const total = expandedData.length
    expandedData.forEach((r, idx) => {})
  }
  return expandedData
}

// 计算：跨车间连续、按工位（工作地点）累计的测量号
const getMeasurementLabelEx = (workshop: any, position: any, row: any) => {
  try {
    if (props.operationType !== 2) return ''
    if (!workshop || !Array.isArray(workshop.positions)) return '—'

    const originalId = row?.originalId || row?.id
    const activeTabs = Array.isArray(tabList.value) ? tabList.value : []

    const isHazardVisibleInPlan = (hz: any): boolean => {
      const pageNo = hz?.operationType
      const mac = hz?.mac
      const type = hz?.type
      const pcTwa = hz?.pcTwa
      const pcStel = hz?.pcStel
      const hasMacPcTwaPcStel =
        (mac != null && mac !== '' && mac !== '—') ||
        (pcTwa != null && pcTwa !== '' && pcTwa !== '—') ||
        (pcStel != null && pcStel !== '' && pcStel !== '—') ||
        parseInt(type + '') !== 2
      const hasTestStandard =
        hz?.testStandard != null && hz?.testStandard !== '' && hz?.testStandard !== '—'
      const hit = hasMacPcTwaPcStel && hasTestStandard
      return pageNo === 2 || (pageNo === 1 && hit)
    }

    const getWorkRowPoint = (workRow: any): number => {
      const hazards = Array.isArray(workRow?.hazards) ? workRow.hazards : []
      for (const hz of hazards) {
        // 逻辑删除：方案页不计入已删除的危害
        if ((hz as any)?.deletedInPage2) continue
        if (isHazardVisibleInPlan(hz)) {
          const v = Number(hz?.sampling?.pointCount)
          return Number.isFinite(v) && v > 0 ? v : 0
        }
      }
      return 0
    }

    let start = 1
    outer: for (const tab of activeTabs) {
      const positions = Array.isArray(tab?.positions) ? tab.positions : []
      for (const pos of positions) {
        const tableData = Array.isArray(pos?.tableData) ? pos.tableData : []
        for (const workRow of tableData) {
          if (tab === workshop && pos === position && workRow?.id === originalId) {
            break outer
          }
          start += getWorkRowPoint(workRow)
        }
      }
    }

    let count = 0
    if (row?.hazard?.sampling?.pointCount != null) {
      const v = Number(row.hazard.sampling.pointCount)
      count = Number.isFinite(v) && v > 0 ? v : 0
    } else {
      const posTable = Array.isArray(position?.tableData) ? position.tableData : []
      const workRow = posTable.find((r: any) => r?.id === originalId)
      count = getWorkRowPoint(workRow)
    }

    if (!count || count <= 0) return '—'

    const nums: number[] = []
    for (let i = 0; i < count; i++) nums.push(start + i)
    const label = nums.join('、')
    console.log(
      `[测量号] 车间=${workshop?.name} 岗位=${position?.name} 工位=${row?.testItem} start=${start} count=${count} -> ${label}`
    )
    return label
  } catch (e) {
    console.warn('[测量号] 计算异常:', e)
    return '—'
  }
}

// 保存编辑
const handleSaveEdit = (row: TableItem, field: string) => {
  if (!row.editing) return

  // 修改数字类型字段列表，移除 contactTime
  const numberFields = ['sampleDuration', 'flowRate', 'sampleDays', 'sampleCount', 'backupCount']

  // 获取原始行ID和危害ID
  const originalRowId = row.id.split('_hazard_')[0]
  const hazardId = row.id.includes('_hazard_') ? Number(row.id.split('_hazard_')[1]) : null

  // 查找原始行
  const position = findPositionByRow(row)
  if (!position) return

  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) return

  // 获取新值
  let newValue: string | number = ''
  if (numberFields.includes(field)) {
    const numValue = row.editingValue
    newValue = typeof numValue === 'number' && !isNaN(numValue) ? numValue : 0
  } else {
    const strValue = row.editingValue
    newValue = typeof strValue === 'string' ? strValue.trim() : ''
  }

  // 更新行数据
  row[field] = newValue

  if (field === 'contactTime') {
    // 先做跨车间岗位维度的总接触时间校验
    const valueNum = Number(newValue)
    const originalValueStr = (() => {
      if (hazardId !== null) {
        const hz = originalRow.hazards?.find((h) => h.id === hazardId)
        return (hz?.contactTime as any) ?? ''
      }
      return (originalRow.contactTime as any) ?? ''
    })()
    const vRes = validateContactTimeTotalForPositionGlobal(
      position,
      originalRow,
      Number.isFinite(valueNum) ? valueNum : 0
    )
    if (!vRes.isValid) {
      ElMessage.warning(vRes.message)
      // 恢复显示
      ;(row as any)[field] = originalValueStr as any
      return
    }

    if (hazardId !== null) {
      // 如果是编辑危害的接触时间
      const hazard = originalRow.hazards?.find((h) => h.id === hazardId)
      if (hazard) {
        hazard.contactTime = newValue as string
      }
    } else {
      // 如果是编辑项目的接触时间，同步更新所有危害的接触时间
      originalRow.contactTime = newValue as string
      originalRow.hazards?.forEach((hazard) => {
        hazard.contactTime = newValue as string
      })
    }
    // 同步更新所有展开行的数据
    position.tableData.forEach((item) => {
      if (item.originalId === originalRowId) {
        if (hazardId !== null) {
          // 如果是危害行，只更新对应的危害
          if (item.id === row.id) {
            item.contactTime = newValue as string
          }
        } else {
          // 如果是项目行，更新所有行
          item.contactTime = newValue as string
        }
      }
    })
  } else if (field === 'fluctuationTime' || field === 'remark') {
    // 波动时机和备注的处理从当前行同步到所有危害
    const fieldValueStr = typeof row[field] === 'string' ? row[field] : String(row[field] || '')
    originalRow[field] = fieldValueStr

    if (originalRow.hazards && originalRow.hazards.length > 0) {
      originalRow.hazards.forEach((hazard) => {
        if (typeof hazard[field] === 'string' || hazard[field] === undefined) {
          hazard[field] = fieldValueStr
        }
      })
    }

    // 同步更新所有展开行的字段值
    position.tableData.forEach((item) => {
      if (item.originalId === originalRow.id) {
        item[field] = fieldValueStr
      }
    })
  }

  // 清除编辑状态
  row.editing = undefined
  row.editingValue = undefined

  // 强制更新表格数据
  position.tableData = [...position.tableData]
}

// 添加点击其他区域时保存的处理函数
const handleTableClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement

  // 如果点击的是输入框或数字输入框，不做处理
  if (target.closest('.el-input-number') || target.closest('.el-input')) {
    return
  }

  // 保存所有正在编辑的字段
  tabList.value.forEach((tab) => {
    tab.positions.forEach((position) => {
      position.tableData.forEach((row) => {
        if (row.editing) {
          handleSaveEdit(row, row.editing)
        }
      })
    })
  })
}

// 添加 watch 监听数据变化
// 在 setup 中添加以下代码:
watch(
  [tabList, activeTab],
  () => {
    surveyStore.printSurveyData()
  },
  {
    deep: true // 深度监听对象变化
  }
)


// 新增岗位类型选择相关
const positionTypeDialogVisible = ref(false)
const selectedPositionType = ref(1) // 默认选择固定岗位
const flowPositions = ref<WorkLocation[]>([{ workInfo: '' }])

// 编辑模式相关
const isEditMode = ref(false) // 是否为编辑模式
const editingPositionId = ref<string>('') // 当前编辑的岗位ID

// 工作地点表格展开状态
const expandedPositions = ref<Set<string>>(new Set())

// 打开岗位管理弹窗（支持新增和编辑模式）
const handleAddPosition = (tabId: string, editPositionId?: string) => {
  console.log('=== 打开岗位管理弹窗 ===')
  console.log('当前tabId:', tabId)
  console.log('编辑岗位ID:', editPositionId)

  // 设置编辑模式状态
  isEditMode.value = !!editPositionId
  editingPositionId.value = editPositionId || ''

  // 获取当前车间
  const currentTab = tabList.value.find((tab) => tab.id === tabId)
  if (!currentTab) {
    ElMessage.error('未找到当前车间')
    return
  }

  // 加载所有岗位（按名称去重，相同名称的岗位只显示一条）
  const positionsByName = new Map<string, any>()

  console.log(`[打开弹窗] 开始加载所有岗位`)
  tabList.value.forEach((workshop) => {
    if (workshop.positions && workshop.positions.length > 0) {
      console.log(`[打开弹窗] 检查车间 "${workshop.name}"，岗位数量: ${workshop.positions.length}`)

      workshop.positions.forEach((position) => {
        if (position.isDeleted) return

        console.log(`[打开弹窗] 检查岗位 "${position.name}"`)
        console.log(`[打开弹窗] 岗位 "${position.name}" 的workplaceData:`, position.workplaceData)
        console.log(
          `[打开弹窗] 岗位 "${position.name}" 的tableData长度:`,
          position.tableData?.length || 0
        )

        // 按名称去重，如果已存在相同名称的岗位，则合并工作地点数据
        if (positionsByName.has(position.name)) {
          console.log(`[打开弹窗] 发现重复岗位名称 "${position.name}"，合并工作地点数据`)

          // 在编辑模式下，如果当前岗位是被编辑的岗位，则替换之前保存的岗位
          if (isEditMode.value && position.id === editPositionId) {
            console.log(`[打开弹窗] 当前岗位是被编辑岗位，替换之前保存的岗位`)
            console.log(`[打开弹窗] 被编辑岗位ID: ${position.id}, 编辑目标ID: ${editPositionId}`)
            positionsByName.set(position.name, position)
          }
          // 这里暂时使用第一个找到的岗位，后续会通过loadWorkplaceDataFromPosition加载所有工作地点
        } else {
          positionsByName.set(position.name, position)
          console.log(`[打开弹窗] 添加岗位: ${position.name} (来自车间: ${workshop.name})`)
        }
      })
    }
  })

  existingPositions.value = Array.from(positionsByName.values())
  console.log(`[打开弹窗] 去重后岗位数量:`, existingPositions.value.length)
  console.log(
    `[打开弹窗] 去重后岗位详情:`,
    existingPositions.value.map((p) => ({
      id: p.id,
      name: p.name,
      workplaceData: p.workplaceData,
      tableData: p.tableData?.length || 0
    }))
  )

  // 在编辑模式下，检查被编辑的岗位是否在去重后的列表中
  if (isEditMode.value && editPositionId) {
    const editingPosition = existingPositions.value.find((p) => p.id === editPositionId)
    if (editingPosition) {
      console.log(`[打开弹窗] ✓ 被编辑岗位已找到:`, editingPosition.name, editingPosition.id)
    } else {
      console.log(`[打开弹窗] ✗ 被编辑岗位未找到，编辑ID:`, editPositionId)
      console.log(
        `[打开弹窗] 可用岗位ID列表:`,
        existingPositions.value.map((p) => p.id)
      )
    }
  }

  // 创建已有岗位的编辑副本
  existingPositionsForEdit.value = existingPositions.value.map((pos) => {
    console.log(`[打开弹窗] 处理已有岗位: ${pos.name}`)
    const workplaceData = loadWorkplaceDataFromPosition(pos) // 不限制车间，加载所有工作地点
    console.log(`[打开弹窗] 岗位 ${pos.name} 的所有工作地点数据:`, workplaceData)

    return {
      id: pos.id,
      name: pos.name,
      totalPeople: pos.totalPeople,
      shiftCount: pos.shiftCount,
      positionType: pos.workMode === '固定' ? 1 : 2,
      workDays: pos.workDays,
      workHours: pos.workHours,
      workPosition: pos.workPosition,
      shiftSystem: pos.shiftSystem,
      workStartTime: pos.workStartTime,
      workEndTime: pos.workEndTime,
      isNew: false,
      isDeleted: pos.isDeleted || false,
      nameError: '',
      // 加载已有的工作地点数据
      workplaceData: workplaceData
    }
  })

  // 重置新增岗位列表
  newPositions.value = []

  // 如果没有任何岗位（既没有已有岗位，也没有新增岗位），则自动添加一个空白行
  if (existingPositions.value.length === 0) {
    console.log('[岗位管理] 没有已有岗位，自动添加一个空白行')
    newPositions.value = [
      {
        name: '',
        totalPeople: 1,
        shiftCount: 1,
        positionType: 1,
        workDays: defaultWorkDays.value,
        workHours: defaultWorkHours.value,
        workPosition: '稳定',
        shiftSystem: '一班',
        workStartTime:
          defaultWorkTimeSegments.value.length > 0
            ? defaultWorkTimeSegments.value[0].startTime
            : '09:00',
        workEndTime:
          defaultWorkTimeSegments.value.length > 0
            ? defaultWorkTimeSegments.value[defaultWorkTimeSegments.value.length - 1].endTime
            : '17:00',
        workTimeSegments:
          defaultWorkTimeSegments.value.length > 0
            ? JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))
            : [
              {
                id: `segment_${uuidv4()}`,
                startTime: '09:00',
                endTime: '17:00',
                duration: 8
              }
            ],
        nameError: ''
      }
    ]
    console.log('[岗位管理] 已添加空白行，newPositions:', newPositions.value)
  } else {
    console.log(`[岗位管理] 已有 ${existingPositions.value.length} 个岗位，不添加空白行`)
  }

  // 重置待删除列表
  positionsToDelete.value = []

  // 重置选择
  selectedPositionType.value = 1
  flowPositions.value = [{ workInfo: '' }]

  // 打开弹窗
  positionTypeDialogVisible.value = true

  // 如果是编辑模式，等待弹窗显示后自动滚动到目标岗位
  if (isEditMode.value && editPositionId) {
    nextTick(() => {
      scrollToEditingPosition()
    })
  }

  // 调试信息
  console.log('[岗位管理] 弹窗已打开')
  console.log('[岗位管理] 已有岗位数量:', existingPositions.value?.length || 0)
  console.log('[岗位管理] 新增岗位数量:', newPositions.value?.length || 0)
  console.log('[岗位管理] 总岗位数量:', allPositions.value?.length || 0)
}

// 滚动到正在编辑的岗位
const scrollToEditingPosition = () => {
  console.log('[滚动定位] 开始滚动到编辑岗位')

  // 如果是编辑模式，自动展开被编辑的岗位的工作地点
  if (isEditMode.value && editingPositionId.value) {
    expandedPositions.value.add(editingPositionId.value)
    console.log('[滚动定位] 自动展开被编辑岗位的工作地点')
  }

  // 等待一定时间确保DOM完全渲染
  setTimeout(() => {
    try {
      // 查找高亮的岗位元素
      const editingElement = document.querySelector('.position-form.editing-highlight')

      if (editingElement) {
        console.log('[滚动定位] 找到编辑岗位元素，开始滚动')

        // 滚动到元素位置，使用smooth滚动效果
        editingElement.scrollIntoView({
          behavior: 'smooth',
          block: 'center',
          inline: 'nearest'
        })

        console.log('[滚动定位] 滚动完成')
      } else {
        console.log('[滚动定位] 未找到编辑岗位元素，尝试延迟重试')

        // 如果找不到元素，可能是DOM还没完全渲染，再次尝试
        setTimeout(() => {
          const retryElement = document.querySelector('.position-form.editing-highlight')
          if (retryElement) {
            console.log('[滚动定位] 重试成功，开始滚动')
            retryElement.scrollIntoView({
              behavior: 'smooth',
              block: 'center',
              inline: 'nearest'
            })
          } else {
            console.log('[滚动定位] 重试失败，无法找到编辑岗位元素')
          }
        }, 300)
      }
    } catch (error) {
      console.error('[滚动定位] 滚动过程中出现错误:', error)
    }
  }, 200) // 给弹窗一定时间完成渲染
}

// 切换工作地点表格的展开状态
const toggleWorkplaceExpanded = (positionId: string) => {
  if (expandedPositions.value.has(positionId)) {
    expandedPositions.value.delete(positionId)
  } else {
    expandedPositions.value.add(positionId)
  }
  console.log(
    `[工作地点展开] 岗位${positionId}状态切换:`,
    expandedPositions.value.has(positionId) ? '展开' : '折叠'
  )
}

// 处理岗位点击事件，自动展开工作地点
const handlePositionClick = (position: any, event: Event) => {
  // 检查点击的目标元素，如果是表单控件则不触发展开
  const target = event.target as HTMLElement
  if (
    target &&
    (target.tagName === 'INPUT' ||
      target.tagName === 'SELECT' ||
      target.tagName === 'BUTTON' ||
      target.tagName === 'TEXTAREA' ||
      target.closest('.el-input') ||
      target.closest('.el-select') ||
      target.closest('.el-button') ||
      target.closest('.el-radio') ||
      target.closest('.el-input-number') ||
      target.closest('.el-time-picker'))
  ) {
    console.log('[岗位点击] 点击了表单控件，跳过自动展开')
    return
  }

  console.log('[岗位点击] 岗位被点击:', position.name || position.id)

  // 设置为当前编辑/选中的岗位
  if (position.id) {
    editingPositionId.value = position.id
    console.log('[岗位点击] 设置当前编辑岗位ID:', position.id)

    // 自动展开该岗位的工作地点
    if (!expandedPositions.value.has(position.id)) {
      expandedPositions.value.add(position.id)
      console.log('[岗位点击] 自动展开工作地点')
    }
  }
}

// 检查工作地点表格是否展开
const isWorkplaceExpanded = (positionId: string) => {
  return expandedPositions.value.has(positionId)
}

// 删除重复的WorkLocation定义，保留一个统一的接口
interface WorkLocation {
  workInfo: string
  workshop?: string
  workshopId?: string | number // 修改为接受string或number
  locationName?: string
}

// 新增岗位项类型定义
interface NewPositionItem {
  id?: string
  name: string
  totalPeople: number
  shiftCount: number
  positionType: number
  workDays: string
  workHours: string
  workPosition: string
  shiftSystem: string
  workStartTime: string | null
  workEndTime: string | null
  isNew?: boolean
  isDeleted?: boolean
  nameError?: string
  workplaceData?: WorkplaceTableRow[]
}

// 表格岗位项类型定义
interface TablePositionItem {
  id?: string
  name: string
  totalPeople: number
  shiftCount: number
  positionType: number
  workDays: string
  workHours: string
  workPosition: string
  shiftSystem: string
  workStartTime: string | null
  workEndTime: string | null
  isNew?: boolean
  isDeleted?: boolean
  isEditing?: boolean
  nameError?: string
  workplaceData?: WorkplaceTableRow[] // 该岗位的工作地点数据
}

// 新增岗位管理相关数据
const newPositions = ref<NewPositionItem[]>([
  {
    id: `new_position_${uuidv4()}`,
    name: '',
    totalPeople: 1,
    shiftCount: 1,
    positionType: 1,
    workDays: defaultWorkDays.value,
    workHours: defaultWorkHours.value,
    workPosition: '稳定',
    shiftSystem: defaultShiftSystem.value,
    workStartTime:
      defaultWorkTimeSegments.value.length > 0
        ? defaultWorkTimeSegments.value[0].startTime
        : '09:00',
    workEndTime:
      defaultWorkTimeSegments.value.length > 0
        ? defaultWorkTimeSegments.value[defaultWorkTimeSegments.value.length - 1].endTime
        : '17:00',
    workTimeSegments:
      defaultWorkTimeSegments.value.length > 0
        ? JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))
        : [
          {
            id: `segment_${uuidv4()}`,
            startTime: '09:00',
            endTime: '17:00',
            duration: 8
          }
        ],
    isNew: true,
    isDeleted: false,
    nameError: '',
    workplaceData: []
  }
])

// 已有岗位列表
const existingPositions = ref<PositionBlock[]>([])

// 待删除的岗位ID列表
const positionsToDelete = ref<string[]>([])

// 为已有岗位创建临时编辑对象
const existingPositionsForEdit = ref<TablePositionItem[]>([])

// 表格中的所有岗位数据（合并已有和新增）
const allPositions = computed<TablePositionItem[]>(() => {
  // 安全检查，确保数组已初始化
  const existingPositions = existingPositionsForEdit.value || []
  const newPositionsArray = newPositions.value || []

  const newOnes = newPositionsArray.map((pos, index) => ({
    id: pos.id || `new_${index}`, // 使用岗位自己的ID或生成新的
    name: pos.name,
    totalPeople: pos.totalPeople,
    shiftCount: pos.shiftCount,
    positionType: pos.positionType,
    workDays: pos.workDays,
    workHours: pos.workHours,
    workPosition: pos.workPosition,
    shiftSystem: pos.shiftSystem,
    workStartTime: pos.workStartTime,
    workEndTime: pos.workEndTime,
    isNew: true,
    isDeleted: false,
    nameError: pos.nameError || '',
    workplaceData: pos.workplaceData || [] // 确保包含工作地点数据
  }))

  // 将新增岗位放在前面，已有岗位放在后面
  const result = [...newOnes, ...existingPositions]

  console.log(
    `[allPositions计算] 已有岗位数量: ${existingPositions.length}, 新增岗位数量: ${newOnes.length}`
  )
  console.log(
    `[allPositions计算] 所有岗位:`,
    result.map((p) => ({
      id: p.id,
      name: p.name,
      isNew: p.isNew,
      workplaceDataCount: p.workplaceData?.length || 0
    }))
  )

  return result
})

// 工作地点表格相关数据和方法
interface WorkplaceTableRow {
  id?: string
  workshop: string
  workplace: string
  contactTime: number
  contactFrequency?: {
    count: number
    duration: number
    interval: number
  }
}

// 获取可用车间列表
const availableWorkshops = computed(() => {
  return tabList.value.map((tab) => ({
    id: tab.id,
    name: tab.name
  }))
})

// 获取指定岗位的工作地点数据
const getWorkplaceDataForPosition = (position: TablePositionItem): WorkplaceTableRow[] => {
  console.log(`[获取工作地点数据] 岗位信息:`, {
    id: position.id,
    name: position.name,
    isNew: position.isNew,
    workplaceData: position.workplaceData
  })

  // 如果岗位没有工作地点数据，初始化为空数组
  if (!position.workplaceData) {
    console.log(`[获取工作地点数据] 岗位 ${position.name} 没有工作地点数据，初始化为空数组`)
    position.workplaceData = []
  }

  console.log(`[获取工作地点数据] 岗位 ${position.name} 返回工作地点数据:`, position.workplaceData)
  return position.workplaceData
}

// 为指定岗位添加工作地点行
const addWorkplaceRowForPosition = (position: TablePositionItem, positionIndex: number) => {
  console.log(`[添加工作地点] 开始为岗位${positionIndex}添加工作地点行`)

  if (!position.name) {
    // 固定作业类型：只允许一行工作地点
    ElMessage.warning('请先填岗位名称')
    return
  }

  // 检查作业类型限制
  if (position.positionType === 1) {
    // 固定作业类型：只允许一行工作地点
    const currentWorkplaceCount = position.workplaceData?.length || 0
    if (currentWorkplaceCount >= 1) {
      ElMessage.warning('固定作业类型只能添加一个工作地点')
      return
    }
  }

  // 自动展开该岗位的工作地点表格
  if (position.id && !expandedPositions.value.has(position.id)) {
    expandedPositions.value.add(position.id)
    console.log(`[添加工作地点] 自动展开岗位 ${position.name || position.id} 的工作地点表格`)
  }

  try {
    // 确保工作地点数据数组存在
    if (!position.workplaceData) {
      position.workplaceData = []
    }

    // 获取当前车间名称作为默认车间
    const currentTab = tabList.value.find((tab) => tab.id === activeTab.value)
    const defaultWorkshop = currentTab ? currentTab.name : ''

    // 根据岗位名称设置默认工作地点（实现联动）
    const defaultWorkplace = position.name?.trim()
      ? `${position.name.trim().replace(/工$/, '')}工位`
      : ''
    // 设置默认接触时间：
    // - 接触类型为“稳定”时，默认等于岗位工作时间
    // - 作业类型为“流动”(positionType === 2) 时，默认 0（同一车间下默认不占满工时）
    // - 其他情况默认 0
    let defaultContactTime = 0
    const workHoursNum = Number(position.workHours) || 0
    if (position.positionType === 2) {
      defaultContactTime = 0
    } else if (position.workPosition === '稳定') {
      defaultContactTime = Math.min(Math.max(workHoursNum, 0), 24)
    } else {
      defaultContactTime = 0
    }
    const contactTime = defaultContactTime
    console.log(
      `[添加工作地点] 岗位名称: ${position.name}, 工作地点: ${defaultWorkplace}, 接触类型: ${position.workPosition}, 作业类型: ${position.positionType === 2 ? '流动' : '固定'}, 默认接触时间: ${contactTime}`
    )
    const newWorkplace = {
      id: `workplace_${uuidv4()}`,
      workshop: defaultWorkshop, // 设置默认车间为当前车间
      workplace: defaultWorkplace, // 设置默认工作地点为岗位名称+位
      contactTime: contactTime,
      contactFrequency: {
        count: 0,
        duration: 0,
        interval: 0
      }
    }

    console.log(`[添加工作地点] 创建新工作地点:`, newWorkplace)

    // 使用响应式更新方式
    if (position.isNew) {
      // 新增岗位：由于新增岗位在前面，直接使用positionIndex
      const newPositionsCount = newPositions.value.length

      if (positionIndex >= 0 && positionIndex < newPositionsCount) {
        if (!newPositions.value[positionIndex].workplaceData) {
          newPositions.value[positionIndex].workplaceData = []
        }
        newPositions.value[positionIndex].workplaceData.push(newWorkplace)
        console.log(
          `[添加工作地点] 已为新增岗位${positionIndex}添加工作地点，当前数量:`,
          newPositions.value[positionIndex].workplaceData.length
        )
      }
    } else {
      // 已有岗位：计算在existingPositionsForEdit中的实际索引
      const newPositionsCount = newPositions.value.length
      const actualIndex = positionIndex - newPositionsCount

      if (actualIndex >= 0 && actualIndex < existingPositionsForEdit.value.length) {
        if (!existingPositionsForEdit.value[actualIndex].workplaceData) {
          existingPositionsForEdit.value[actualIndex].workplaceData = []
        }
        existingPositionsForEdit.value[actualIndex].workplaceData.push(newWorkplace)
        console.log(
          `[添加工作地点] 已为已有岗位${actualIndex}添加工作地点，当前数量:`,
          existingPositionsForEdit.value[actualIndex].workplaceData.length
        )
      }
    }
  } finally {
    // 清除添加标记
    setTimeout(() => {
      delete position._addingWorkplace
    }, 100)
  }
}

// 删除指定岗位的工作地点行
const deleteWorkplaceRowForPosition = (position: TablePositionItem, workplaceIndex: number) => {
  console.log(`[删除工作地点] 开始删除工作地点，索引:`, workplaceIndex)

  // 找到岗位在allPositions中的索引
  const positionIndex = allPositions.value.findIndex((p) => p.id === position.id)
  if (positionIndex < 0) {
    console.error(`[删除工作地点] 未找到岗位，position.id:`, position.id)
    return
  }

  // 使用响应式更新方式
  if (position.isNew) {
    // 新增岗位：由于新增岗位在前面，直接使用positionIndex
    const newPositionsCount = newPositions.value.length

    if (positionIndex >= 0 && positionIndex < newPositionsCount) {
      const workplaceData = newPositions.value[positionIndex].workplaceData
      if (workplaceData && workplaceData.length > workplaceIndex) {
        workplaceData.splice(workplaceIndex, 1)
        console.log(
          `[删除工作地点] 已删除新增岗位${positionIndex}的工作地点，剩余数量:`,
          workplaceData.length
        )

        // 删除后同步工作地点数据到各车间
        console.log(`[删除工作地点] 开始同步岗位 "${position.name}" 的工作地点数据到各车间`)
        if (!positionTypeDialogVisible.value) {
          if (!positionTypeDialogVisible.value) {
            syncWorkplaceDataToWorkshops(position.name, workplaceData)
          }
        }
      }
    }
  } else {
    // 已有岗位：计算在existingPositionsForEdit中的实际索引
    const newPositionsCount = newPositions.value.length
    const actualIndex = positionIndex - newPositionsCount

    if (actualIndex >= 0 && actualIndex < existingPositionsForEdit.value.length) {
      const workplaceData = existingPositionsForEdit.value[actualIndex].workplaceData
      if (workplaceData && workplaceData.length > workplaceIndex) {
        workplaceData.splice(workplaceIndex, 1)
        console.log(
          `[删除工作地点] 已删除已有岗位${actualIndex}的工作地点，剩余数量:`,
          workplaceData.length
        )

        // 删除后同步工作地点数据到各车间
        console.log(`[删除工作地点] 开始同步岗位 "${position.name}" 的工作地点数据到各车间`)
        syncWorkplaceDataToWorkshops(position.name, workplaceData)
      }
    }
  }
}
// 验证弹窗中岗位的所有工作地点接触时间总和是否超出岗位工作时间（按车间分别校验）
const validateWorkplaceContactTimeTotalForPositionByWorkshop = (
  position: any,
  currentRowIndex: number,
  newContactTime: number
): { isValid: boolean; message: string } => {
  const workplaceData = position.workplaceData || []
  let total = 0
  workplaceData.forEach((wp: any, idx: number) => {
    if (idx === currentRowIndex) {
      total += newContactTime
    } else {
      const t = Number(wp.contactTime)
      total += Number.isNaN(t) ? 0 : t
    }
  })

  const workHoursNum = Number(position.workHours)
  const maxHours = Number.isNaN(workHoursNum) ? 8 : workHoursNum
  const ok = total <= maxHours
  let message = ''
  if (!ok) {
    const excess = (total - maxHours).toFixed(1)
    message = `岗位【${position.name}】，接触时间总和超出岗位工作时间${excess}h，请调整接触频度`
  }
  return { isValid: ok, message }
}

// 用于保存弹窗中正在编辑的接触频度的原始值
const workplaceFrequencyBackup = ref<Map<string, any>>(new Map())

// 处理工作地点接触频度开始编辑（焦点事件）
const handleWorkplaceFrequencyFocus = (
  position: any,
  workplaceRow: any,
  workplaceIndex: number,
  field: string
) => {
  const backupKey = `${position.name}_${workplaceIndex}_${field}`
  if (!workplaceFrequencyBackup.value.has(backupKey)) {
    const originalValue = workplaceRow.contactFrequency?.[field] || (field === 'duration' ? 0 : 0)
    workplaceFrequencyBackup.value.set(backupKey, originalValue)
    console.log(`[工作地点接触频度] 保存编辑前的原始值 ${backupKey}: ${originalValue}`)
  }
}

// 处理工作地点接触频度变化
const handleWorkplaceContactFrequencyChange = (
  position: any,
  workplaceRow: any,
  workplaceIndex: number,
  field: string
) => {
  console.log('[工作地点接触频度变化]', {
    positionName: position.name,
    workplaceIndex,
    field,
    newValue: workplaceRow.contactFrequency[field]
  })

  // 确保接触频度对象存在
  if (!workplaceRow.contactFrequency) {
    workplaceRow.contactFrequency = {
      count: 1,
      duration: 1,
      interval: 1
    }
  }

  // 如果岗位接触类型为"非稳定"，根据接触频度自动计算接触时间
  if (position.workPosition === '非稳定') {
    const count = Number.isNaN(Number(workplaceRow.contactFrequency.count))
      ? 0
      : Number(workplaceRow.contactFrequency.count)
    const duration = Number.isNaN(Number(workplaceRow.contactFrequency.duration))
      ? 0
      : Number(workplaceRow.contactFrequency.duration)

    // 接触时间 = 次数 × 时间，限制在0~24小时
    const calculatedContactTime = Math.min(count * duration, 24)
    console.log('[工作地点接触频度变化] 自动计算接触时间:', calculatedContactTime)

    // 验证接触时间总和是否超出岗位工作时间
    const validation = validateWorkplaceContactTimeTotalForPositionByWorkshop(
      position,
      workplaceIndex,
      calculatedContactTime
    )
    if (!validation.isValid) {
      console.log(`[工作地点接触频度变化] 验证失败，恢复原值`)
      ElMessage.warning({
        message: validation.message,
        duration: 4000 // 8秒后关闭
      })

      // 从备份中恢复原始值
      const backupKey = `${position.name}_${workplaceIndex}_${field}`
      const originalValue = workplaceFrequencyBackup.value.get(backupKey) ?? 0
      workplaceRow.contactFrequency[field] = originalValue
      console.log(`[工作地点接触频度变化] 已恢复接触频度 ${field}: ${originalValue}`)

      // 重新计算接触时间（使用恢复的值）
      const restoredCount = Number.isNaN(Number(workplaceRow.contactFrequency.count))
        ? 0
        : Number(workplaceRow.contactFrequency.count)
      const restoredDuration = Number.isNaN(Number(workplaceRow.contactFrequency.duration))
        ? 0
        : Number(workplaceRow.contactFrequency.duration)
      const restoredContactTime = Math.min(restoredCount * restoredDuration, 24)
      workplaceRow.contactTime = restoredContactTime
      console.log('[工作地点接触频度变化] 恢复接触时间:', restoredContactTime)

      // 清除备份（因为已经恢复了）
      workplaceFrequencyBackup.value.delete(backupKey)

      // 强制触发响应式更新
      position.workplaceData = [...position.workplaceData]
      console.log('[工作地点接触频度变化] 已触发响应式更新')

      // 不继续执行后续同步逻辑
      return
    }

    // 验证通过，清除备份并设置新的接触时间
    const backupKey = `${position.name}_${workplaceIndex}_${field}`
    workplaceFrequencyBackup.value.delete(backupKey)
    workplaceRow.contactTime = calculatedContactTime
    console.log('[工作地点接触频度变化] 验证通过，设置新接触时间:', calculatedContactTime)
  }

  // 同步数据到实际的岗位数据中
  if (!positionTypeDialogVisible.value) {
    syncWorkplaceFrequencyDataToActualPosition(position.name, workplaceRow)
  }
}

// 同步工作地点频度数据到实际岗位
const syncWorkplaceFrequencyDataToActualPosition = (positionName: string, workplaceRow: any) => {
  console.log('[同步工作地点频度数据] 开始同步:', {
    positionName,
    workplace: workplaceRow.workplace
  })

  // 查找实际的岗位数据
  const actualPosition = findActualPositionByName(positionName)
  if (actualPosition && actualPosition.tableData && Array.isArray(actualPosition.tableData)) {
    // 查找对应的表格行（通过工作地点匹配）
    const targetRow = actualPosition.tableData.find((tableRow: any) => {
      return (
        tableRow.testItem === workplaceRow.workplace ||
        (typeof tableRow.testItem === 'object' &&
          tableRow.testItem?.content === workplaceRow.workplace)
      )
    })

    if (targetRow) {
      // 更新该行的接触频度和接触时间
      targetRow.contactFrequency = { ...workplaceRow.contactFrequency }
      targetRow.contactTime = workplaceRow.contactTime

      // 如果该行有危害数据，也要更新危害的接触频度
      if (targetRow.hazards && Array.isArray(targetRow.hazards)) {
        targetRow.hazards.forEach((hazard: any) => {
          hazard.contactFrequency = { ...workplaceRow.contactFrequency }
          hazard.contactTime = workplaceRow.contactTime
        })
      }

      console.log('[同步工作地点频度数据] 同步成功')

      // 同步接触时间到劳动者行
      console.log('[同步工作地点频度数据] 触发同步接触时间到劳动者行')
      syncContactTimeToLaborers(actualPosition)
    } else {
      console.log('[同步工作地点频度数据] 未找到对应的表格行')
    }
  } else {
    console.log('[同步工作地点频度数据] 未找到实际岗位数据（可能是新增岗位，数据已保存在弹窗中）')
    // 对于新增岗位，数据已经保存在弹窗的工作地点数据中，确认保存时会正确同步
  }
}

// 处理指定岗位的车间变化
const handleWorkshopChangeForPosition = (
  position: TablePositionItem,
  row: WorkplaceTableRow,
  index: number
) => {
  console.log('[岗位车间变化]', { positionName: position.name, workshop: row.workshop, index })
  // 车间变化时不清空工作地点，保留用户已输入的数据
  // row.workplace = '' // 注释掉这行，不再清空工作地点

  // 根据业务规则设置默认接触时间：
  // - 接触类型为“稳定”时，若当前为 0，则设为岗位工作时间
  // - 作业类型为“流动”(positionType === 2) 时，保持为 0
  if (row.contactTime === 0) {
    if (position.positionType === 2) {
      row.contactTime = 0
    } else if (position.workPosition === '稳定') {
      const hoursNum = Number(position.workHours) || 0
      row.contactTime = Math.min(Math.max(hoursNum, 0), 24)
    }
  }

  // 再次校正：当接触类型非“稳定”时，将弹窗中的已添加地点接触时间统一置为 0
  // if (Array.isArray(position.workplaceData) && position.workPosition !== '稳定') {
  //   position.workplaceData.forEach((wp: any) => {
  //     wp.contactTime = 0
  //   })
  // }
}

// 手动调整工作地点接触时间时校验（稳定类型：不得超过岗位工作时间）
const handleWorkplaceContactTimeInputChange = (
  position: TablePositionItem,
  row: WorkplaceTableRow,
  index: number
) => {
  let val = Number(row.contactTime)
  if (isNaN(val)) val = 0
  const workHoursNum = Math.min(Math.max(Number(position.workHours) || 0, 0), 24)

  if (position.workPosition === '稳定' && val > workHoursNum) {
    ElMessage.warning(`接触时间不可超过岗位工作时间(${workHoursNum}h)`)
    row.contactTime = workHoursNum
  } else if (val < 0) {
    row.contactTime = 0
  }
}

// 处理指定岗位的工作地点变化
const handleWorkplaceChangeForPosition = (
  position: TablePositionItem,
  row: WorkplaceTableRow,
  index: number
) => {
  console.log('[岗位工作地点变化]', {
    positionName: position.name,
    workplace: row.workplace,
    index
  })

  // 弹窗中的工作地点变化只需要记录，不需要额外处理
  // 联动逻辑已经通过UI层面的数据绑定完成
  console.log('[工作地点联动] 弹窗中的工作地点变化已记录')
}

// 从岗位数据中加载工作地点信息
const loadWorkplaceDataFromPosition = (
  position: any,
  targetWorkshopName?: string
): WorkplaceTableRow[] => {
  const workplaceData: WorkplaceTableRow[] = []
  const positionName = position.name

  console.log(`[加载工作地点] 开始为岗位 "${positionName}" 加载工作地点数据`)
  if (targetWorkshopName) {
    console.log(`[加载工作地点] 只加载车间 "${targetWorkshopName}" 的工作地点`)
  }
  console.log(
    `[加载工作地点] 当前车间列表:`,
    tabList.value.map((t) => ({ id: t.id, name: t.name, positionsCount: t.positions?.length || 0 }))
  )

  // 遍历所有车间，查找包含该岗位的车间
  tabList.value.forEach((workshop) => {
    // 如果指定了目标车间，只处理目标车间
    if (targetWorkshopName && workshop.name !== targetWorkshopName) {
      return
    }

    console.log(
      `[加载工作地点] 检查车间 "${workshop.name}"，岗位数量:`,
      workshop.positions?.length || 0
    )

    if (workshop.positions && workshop.positions.length > 0) {
      // 在当前车间中查找匹配的岗位
      const matchingPositions = workshop.positions.filter(
        (pos) => pos.name === positionName && !pos.isDeleted
      )

      console.log(
        `[加载工作地点] 车间 "${workshop.name}" 中匹配的岗位数量:`,
        matchingPositions.length
      )

      if (matchingPositions.length > 0) {
        console.log(
          `[加载工作地点] 在车间 "${workshop.name}" 中找到 ${matchingPositions.length} 个匹配岗位`
        )

        // 为每个匹配的岗位创建工作地点行
        matchingPositions.forEach((matchedPos, index) => {
          // 从表格数据中获取工作地点信息（testItem字段）
          if (matchedPos.tableData && matchedPos.tableData.length > 0) {
            // 遍历表格数据，只有workLocation=1的行才是工作地点
            matchedPos.tableData.forEach((tableRow, rowIndex) => {
              // 获取testItem的实际内容（兼容字符串和对象格式）
              const getTestItemContent = (testItem: any): string => {
                if (typeof testItem === 'string') {
                  return testItem
                } else if (testItem && typeof testItem === 'object') {
                  return testItem.content || testItem.fullText || ''
                }
                return ''
              }

              const testItemContent = getTestItemContent(tableRow.testItem)

              // 过滤条件：只有workLocation=1且testItem有值的行才添加
              if (tableRow.workLocation === 1 && testItemContent && testItemContent.trim()) {
                let contactTime = parseFloat(position.workHours) || 8

                // 如果有专门的工作地点数据，尝试获取接触时间和接触频度
                let contactFrequency = {
                  count: 1,
                  duration: 1,
                  interval: 1
                }

                if (matchedPos.workplaceData && matchedPos.workplaceData.length > rowIndex) {
                  const wpRow = matchedPos.workplaceData[rowIndex]
                  // 保留 0，不用 || 覆盖；并转为数值
                  if (
                    wpRow.contactTime !== undefined &&
                    wpRow.contactTime !== null &&
                    wpRow.contactTime !== ''
                  ) {
                    const t = Number(wpRow.contactTime)
                    if (!Number.isNaN(t)) contactTime = t
                  }
                  contactFrequency = wpRow.contactFrequency || contactFrequency
                }

                // 从tableRow中获取接触频度数据
                if (tableRow.contactFrequency) {
                  contactFrequency = { ...tableRow.contactFrequency }
                }

                // 从tableRow中获取接触时间
                if (
                  tableRow.contactTime !== undefined &&
                  tableRow.contactTime !== null &&
                  tableRow.contactTime !== ''
                ) {
                  const t = Number(tableRow.contactTime)
                  if (!Number.isNaN(t)) contactTime = t
                }

                workplaceData.push({
                  id: `workplace_${matchedPos.id}_${rowIndex}`,
                  workshop: workshop.name, // 使用车间名称
                  workplace: testItemContent.trim(), // 使用testItem作为工作地点
                  contactTime: contactTime,
                  contactFrequency: contactFrequency
                })

                console.log(
                  `[加载工作地点] 添加工作地点: 车间="${workshop.name}", 岗位="${positionName}", 工作地点="${testItemContent.trim()}", workLocation=${tableRow.workLocation}`
                )
              } else if (testItemContent && testItemContent.trim()) {
                console.log(
                  `[加载工作地点] 跳过非工作地点行: testItem="${testItemContent.trim()}", workLocation=${tableRow.workLocation}`
                )
              }
            })
          } else {
            // 如果没有表格数据，但有专门的工作地点数据
            if (matchedPos.workplaceData && matchedPos.workplaceData.length > 0) {
              matchedPos.workplaceData.forEach((workplaceItem, wpIndex) => {
                workplaceData.push({
                  id: `workplace_${matchedPos.id}_wp_${wpIndex}`,
                  workshop: workshop.name,
                  workplace: workplaceItem.workplace || '',
                  contactTime: workplaceItem.contactTime ?? (parseFloat(position.workHours) || 8)
                })
              })
            }
          }
        })
      }
    }
  })

  // 如果没有找到任何匹配的车间岗位，创建一个默认空行
  if (workplaceData.length === 0) {
    console.log(`[加载工作地点] 岗位 "${positionName}" 未找到匹配的车间，创建默认空行`)
    workplaceData.push({
      id: `workplace_${position.id}_default`,
      workshop: '',
      workplace: '',
      contactTime: parseFloat(position.workHours) || 8
    })
  }

  console.log(
    `[加载工作地点] 岗位 "${positionName}" 最终加载了 ${workplaceData.length} 条工作地点数据:`,
    workplaceData
  )
  return workplaceData
}

// 将工作地点数据同步到对应的车间岗位中
const syncWorkplaceDataToWorkshops = (positionName: string, workplaceData: WorkplaceTableRow[]) => {
  console.log(`[同步工作地点] 开始为岗位 "${positionName}" 同步工作地点数据`)
  console.log(`[同步工作地点] 要同步的工作地点数据:`, workplaceData)

  // 调试：检查工作地点数据中的接触频度
  workplaceData.forEach((row, index) => {
    console.log(
      `[同步工作地点] 工作地点${index}: ${row.workplace}, 接触时间: ${row.contactTime}, 接触频度:`,
      row.contactFrequency
    )
  })

  // 首先找到原始岗位信息（用于复制岗位到其他车间）
  let sourcePosition: any = null
  tabList.value.forEach((workshop) => {
    if (workshop.positions && workshop.positions.length > 0) {
      const found = workshop.positions.find((pos) => pos.name === positionName && !pos.isDeleted)
      if (found && !sourcePosition) {
        sourcePosition = found
      }
    }
  })

  if (!sourcePosition) {
    console.error(`[同步工作地点] 未找到源岗位 "${positionName}"`)
    return
  }

  console.log(`[同步工作地点] 找到源岗位:`, sourcePosition.name)

  // 按车间分组工作地点数据
  const workplacesByWorkshop = new Map<string, WorkplaceTableRow[]>()
  workplaceData.forEach((workplaceRow) => {
    if (workplaceRow.workshop && workplaceRow.workplace && workplaceRow.workplace.trim()) {
      if (!workplacesByWorkshop.has(workplaceRow.workshop)) {
        workplacesByWorkshop.set(workplaceRow.workshop, [])
      }
      workplacesByWorkshop.get(workplaceRow.workshop)!.push(workplaceRow)
    }
  })

  console.log(`[同步工作地点] 按车间分组的工作地点:`, Array.from(workplacesByWorkshop.entries()))

  // 为每个涉及的车间处理岗位和工作地点
  workplacesByWorkshop.forEach((workshopWorkplaces, workshopName) => {
    console.log(`[同步工作地点] 处理车间 "${workshopName}" 的工作地点`)

    // 查找目标车间
    const targetWorkshop = tabList.value.find((workshop) => workshop.name === workshopName)
    if (!targetWorkshop) {
      console.warn(`[同步工作地点] 未找到车间: ${workshopName}`)
      return
    }

    // 确保车间有positions数组
    if (!targetWorkshop.positions) {
      targetWorkshop.positions = []
    }

    // 查找车间中是否已有该岗位
    let targetPosition = targetWorkshop.positions.find(
      (pos) => pos.name === positionName && !pos.isDeleted
    )

    if (!targetPosition) {
      // 如果车间中没有该岗位，创建一个新的岗位
      console.log(`[同步工作地点] 车间 "${workshopName}" 中没有岗位 "${positionName}"，开始创建`)

      const newPositionId = `position_${uuidv4()}`

      targetPosition = {
        id: newPositionId,
        name: sourcePosition.name,
        totalPeople: sourcePosition.totalPeople,
        shiftCount: sourcePosition.shiftCount,
        workMode: sourcePosition.workMode,
        workPosition: sourcePosition.workPosition,
        workHours: sourcePosition.workHours,
        workDays: sourcePosition.workDays,
        shiftSystem: sourcePosition.shiftSystem,
        workStartTime: sourcePosition.workStartTime,
        workEndTime: sourcePosition.workEndTime,
        isDeleted: false,
        tableData: [
          // 添加劳动者行
          {
            id: `table_${newPositionId}_worker`,
            testItem: '劳动者',
            workLocation: 2, // 标记为劳动者
            contactTime: sourcePosition.workHours || 8,
            workContent: '',
            laborIntensity: '',
            source: '',
            contactFrequency: {
              count: 1,
              duration: 1,
              interval: 1
            },
            fluctuationTime: '',
            personalProtection: '',
            hazards: [],
            isDeleted: false
          }
        ],
        workplaceData: []
      }

      targetWorkshop.positions.push(targetPosition)
      console.log(`[同步工作地点] 已在车间 "${workshopName}" 中创建岗位 "${positionName}"`)
    } else {
      console.log(`[同步工作地点] 车间 "${workshopName}" 中已存在岗位 "${positionName}"`)
    }

    // 更新岗位的工作地点数据
    targetPosition.workplaceData = workshopWorkplaces
    console.log(
      `[同步工作地点] 已保存岗位 "${positionName}" 在车间 "${workshopName}" 的工作地点数据:`,
      targetPosition.workplaceData
    )

    // 更新表格数据中的工作地点信息
    if (targetPosition.tableData) {
      console.log(
        `[同步工作地点] 开始更新岗位 "${positionName}" 在车间 "${workshopName}" 的表格数据`
      )

      // 获取现有的工作地点行
      const existingWorkplaceRows = targetPosition.tableData.filter((row) => row.workLocation === 1)
      console.log(`[同步工作地点] 现有工作地点行数量: ${existingWorkplaceRows.length}`)

      // 创建工作地点名称到现有行的映射
      const existingRowMap = new Map<string, any>()
      existingWorkplaceRows.forEach((row) => {
        // 获取testItem的实际内容（兼容字符串和对象格式）
        const getTestItemContent = (testItem: any): string => {
          if (typeof testItem === 'string') {
            return testItem
          } else if (testItem && typeof testItem === 'object') {
            return testItem.content || testItem.fullText || ''
          }
          return ''
        }

        const testItemContent = getTestItemContent(row.testItem)
        if (testItemContent) {
          existingRowMap.set(testItemContent.trim(), row)
        }
      })

      // 处理新的工作地点数据
      const newWorkplaceNames = new Set<string>()
      workshopWorkplaces.forEach((workplaceRow, index) => {
        if (workplaceRow.workplace && workplaceRow.workplace.trim()) {
          const workplaceName = workplaceRow.workplace.trim()
          newWorkplaceNames.add(workplaceName)

          if (existingRowMap.has(workplaceName)) {
            // 更新现有行的接触时间和接触频度等信息，但保留危害数据
            const existingRow = existingRowMap.get(workplaceName)
            // 避免把 0 当作 falsy 覆盖为默认值
            if (
              workplaceRow.contactTime !== undefined &&
              workplaceRow.contactTime !== null &&
              workplaceRow.contactTime !== ''
            ) {
              existingRow.contactTime = workplaceRow.contactTime
            }

            // 更新接触频度数据
            if (workplaceRow.contactFrequency) {
              existingRow.contactFrequency = { ...workplaceRow.contactFrequency }
              console.log(
                `[同步工作地点] 更新现有工作地点行: testItem="${workplaceName}"，接触频度:`,
                existingRow.contactFrequency
              )
            }

            // 如果该行有危害数据，也要更新危害的接触频度和接触时间
            if (existingRow.hazards && Array.isArray(existingRow.hazards)) {
              existingRow.hazards.forEach((hazard: any) => {
                hazard.contactTime = existingRow.contactTime
                if (workplaceRow.contactFrequency) {
                  hazard.contactFrequency = { ...workplaceRow.contactFrequency }
                }
              })
            }

            console.log(
              `[同步工作地点] 更新现有工作地点行: testItem="${workplaceName}"，保留危害数据`
            )
          } else {
            // 添加新的工作地点行
            const newTableRow = {
              id: `table_${targetPosition.id}_workplace_${index}`,
              testItem: workplaceName, // 保持字符串格式，与现有数据一致
              workLocation: 1, // 标记为工作地点
              hazards: [],
              contactTime: workplaceRow.contactTime ?? 8,
              workContent: '',
              laborIntensity: '',
              source: '',
              contactFrequency: workplaceRow.contactFrequency
                ? { ...workplaceRow.contactFrequency }
                : {
                  count: 1,
                  duration: 1,
                  interval: 1
                },
              fluctuationTime: '',
              personalProtection: '',
              isDeleted: false
            }

            targetPosition.tableData.push(newTableRow)
            console.log(
              `[同步工作地点] 添加新工作地点行: testItem="${workplaceName}"，接触频度:`,
              newTableRow.contactFrequency
            )
          }
        }
      })

      // 删除不再存在的工作地点行（但只删除没有危害数据的行）
      targetPosition.tableData = targetPosition.tableData.filter((row) => {
        if (row.workLocation !== 1) {
          return true // 保留非工作地点行
        }

        // 获取testItem的实际内容（兼容字符串和对象格式）
        const getTestItemContent = (testItem: any): string => {
          if (typeof testItem === 'string') {
            return testItem
          } else if (testItem && typeof testItem === 'object') {
            return testItem.content || testItem.fullText || ''
          }
          return ''
        }

        const workplaceName = getTestItemContent(row.testItem)?.trim()
        if (!workplaceName || newWorkplaceNames.has(workplaceName)) {
          return true // 保留仍然存在的工作地点行
        }

        // 检查是否有危害数据
        const hasHazards = row.hazards && row.hazards.length > 0
        if (hasHazards) {
          console.log(`[同步工作地点] 保留有危害数据的工作地点行: testItem="${workplaceName}"`)
          return true // 保留有危害数据的行
        } else {
          console.log(`[同步工作地点] 删除无危害数据的工作地点行: testItem="${workplaceName}"`)
          return false // 删除没有危害数据的行
        }
      })

      console.log(
        `[同步工作地点] 岗位 "${positionName}" 在车间 "${workshopName}" 的表格数据更新完成，总行数:`,
        targetPosition.tableData.length
      )

      // 将劳动者行( workLocation=2 )移动到队尾，仅调整顺序不改变结构
      const laborerRows = targetPosition.tableData.filter((row) => row.workLocation === 2)
      const otherRows = targetPosition.tableData.filter((row) => row.workLocation !== 2)
      targetPosition.tableData = [...otherRows, ...laborerRows]
      const hasLaborerRow = targetPosition.tableData.some(r => r.workLocation === 2)
      if (!hasLaborerRow) {
        targetPosition.tableData.push({
          id: `table_${targetPosition.id}_worker_${Date.now()}`, // 生成新ID
          testItem: '劳动者',
          workLocation: 2,
          contactTime: targetPosition.workHours || 8,
          workContent: '',
          laborIntensity: '',
          source: '',
          contactFrequency: { count: 1, duration: 1, interval: 1 },
          fluctuationTime: '',
          personalProtection: '',
          hazards: [],
          isDeleted: false
        })
      }
      // 强制触发响应式更新
      targetPosition.tableData = [...targetPosition.tableData]
    }
  })

  // 检查所有车间，确保那些不再有该岗位工作地点的车间中的岗位被物理删除
  const workshopsWithWorkplaces = new Set(workplaceData.map((row) => row.workshop).filter(Boolean))
  console.log(
    `[同步工作地点] 岗位 "${positionName}" 应该存在于这些车间:`,
    Array.from(workshopsWithWorkplaces)
  )

  tabList.value.forEach((workshop) => {
    const position = workshop.positions?.find((pos) => pos.name === positionName)
    if (position && !position.isDeleted) {
      if (!workshopsWithWorkplaces.has(workshop.name)) {
        // 该车间不再有该岗位的工作地点，物理删除该岗位
        console.log(
          `[同步工作地点] 车间 "${workshop.name}" 不再有岗位 "${positionName}" 的工作地点，物理删除`
        )
        const positionIndex = workshop.positions.findIndex((pos) => pos.name === positionName)
        if (positionIndex !== -1) {
          workshop.positions.splice(positionIndex, 1)
          console.log(`[同步工作地点] 已从车间 "${workshop.name}" 中物理删除岗位 "${positionName}"`)
        }
      }
    }
  })

  // 同步完成后，强制刷新所有表格
  console.log(`[同步工作地点] 工作地点数据同步完成，开始刷新表格`)
  nextTick(() => {
    refreshAllTables()
  })
}

// 添加新岗位行
const addNewPositionRow = () => {
  const newPosition: TablePositionItem = {
    id: `position_${uuidv4()}`, // 添加唯一ID
    name: '',
    totalPeople: 1,
    shiftCount: 1,
    positionType: 1,
    workDays: defaultWorkDays.value,
    workHours: defaultWorkHours.value,
    workPosition: '稳定',
    shiftSystem: defaultShiftSystem.value,
    workStartTime:
      defaultWorkTimeSegments.value.length > 0
        ? defaultWorkTimeSegments.value[0].startTime
        : '09:00',
    workEndTime:
      defaultWorkTimeSegments.value.length > 0
        ? defaultWorkTimeSegments.value[defaultWorkTimeSegments.value.length - 1].endTime
        : '17:00',
    workTimeSegments:
      defaultWorkTimeSegments.value.length > 0
        ? JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))
        : [
          {
            id: `segment_${uuidv4()}`,
            startTime: '09:00',
            endTime: '17:00',
            duration: 8
          }
        ],
    isNew: true, // 标记为新增岗位
    isDeleted: false,
    nameError: '',
    workplaceData: [] // 初始化工作地点数据数组
  }

  // 添加到数组最前面而不是最后面
  newPositions.value.unshift(newPosition)
  console.log('[添加新岗位] 新增岗位行已添加到列表顶部:', newPosition)
  console.log(
    `[添加新岗位] 新岗位工作时段: ${newPosition.workTimeSegments.length > 0 ? newPosition.workTimeSegments.map((s) => `${s.startTime}-${s.endTime}`).join(' || ') : '无时段'}`
  )

  // 设置新岗位为当前编辑岗位（获得蓝色高亮效果）
  editingPositionId.value = newPosition.id
  console.log('[添加新岗位] 设置新岗位为当前编辑岗位:', newPosition.id)
}

// 更新岗位字段的通用方法
const updatePositionField = (
  position: TablePositionItem,
  index: number,
  field: string,
  value: any
) => {
  console.log(`[更新岗位字段] 岗位${index}, 字段${field}, 新值:`, value)
  console.log(`[更新岗位字段] position.isNew:`, position.isNew)

  // 保存旧值，用于联动处理
  const oldValue = position[field]

  // 如果是新增岗位，直接使用索引更新
  if (position.isNew) {
    // 由于现在新增岗位在前面，所以直接使用index作为newPositions的索引
    // 但需要确保index在新增岗位的范围内
    const newPositionsCount = newPositions.value.length

    console.log(`[更新岗位字段] 新增岗位数量: ${newPositionsCount}, 当前索引: ${index}`)

    if (index >= 0 && index < newPositionsCount) {
      // 使用Vue的响应式更新
      newPositions.value[index] = {
        ...newPositions.value[index],
        [field]: value
      }
      console.log(`[更新岗位字段] 已更新新增岗位${index}的${field}字段`)
      console.log(`[更新岗位字段] 更新后的岗位:`, newPositions.value[index])
    } else {
      console.error(
        `[更新岗位字段] 新增岗位索引越界，index=${index}, newPositions.length=${newPositionsCount}`
      )
    }
  } else {
    // 如果是已有岗位，需要计算在existingPositionsForEdit中的实际索引
    // 由于新增岗位在前面，所以已有岗位的实际索引 = index - 新增岗位数量
    const newPositionsCount = newPositions.value.length
    const actualIndex = index - newPositionsCount

    console.log(
      `[更新岗位字段] 新增岗位数量: ${newPositionsCount}, 当前索引: ${index}, 计算的已有岗位索引: ${actualIndex}`
    )

    if (actualIndex >= 0 && actualIndex < existingPositionsForEdit.value.length) {
      existingPositionsForEdit.value[actualIndex] = {
        ...existingPositionsForEdit.value[actualIndex],
        [field]: value
      }
      console.log(`[更新岗位字段] 已更新已有岗位${actualIndex}的${field}字段`)
    } else {
      console.error(
        `[更新岗位字段] 已有岗位索引越界，actualIndex=${actualIndex}, existingPositions.length=${existingPositionsForEdit.value.length}`
      )
    }
  }

  // 根据字段类型触发相应的处理逻辑
  // 注意：需要在下一个tick中调用，确保数据已经更新
  nextTick(() => {
    if (field === 'name') {
      console.log(`[更新岗位字段] 准备验证岗位名称，使用的对象:`, allPositions.value[index])
      console.log(`[更新岗位字段] 验证前的nameError:`, allPositions.value[index].nameError)
      handlePositionNameChange(allPositions.value[index], index)
      console.log(`[更新岗位字段] 验证后的nameError:`, allPositions.value[index].nameError)
      // 如果是岗位名称变化，且新旧值不同，触发联动
      // if (oldValue !== value && oldValue && value) {
      //   // 需要找到对应的实际岗位数据来触发联动
      //   const actualPosition = findActualPositionByName(value)
      //   if (actualPosition) {
      //     handlePositionNameChangeWithLinkage(actualPosition, oldValue, value)
      //   }
      // }
    } else if (field === 'positionType') {
      handlePositionTypeChange(allPositions.value[index], index)
    } else if (field === 'workPosition') {
      // 传入(新值, 岗位对象)以符合签名
      handleWorkPositionChange(allPositions.value[index].workPosition, allPositions.value[index])
    } else if (
      ['totalPeople', 'shiftCount', 'workDays', 'workHours', 'shiftSystem'].includes(field)
    ) {
      // --- 新增：在弹窗中也触发计算 ---
      if (field === 'shiftCount' || field === 'shiftSystem') {
        // 计算总人数
        const count = Number(position.shiftCount) || 0
        const systemVal = parseShiftSystemValue(position.shiftSystem)
        // 更新当前对象的 totalPeople
        if (position.isNew) {
          newPositions.value[index].totalPeople = count * systemVal
        } else {
          // 计算实际索引（因为 existingPositionsForEdit 是部分数据）
          const newPositionsCount = newPositions.value.length
          const actualIndex = index - newPositionsCount
          if (existingPositionsForEdit.value[actualIndex]) {
            existingPositionsForEdit.value[actualIndex].totalPeople = count * systemVal
          }
        }
      }
      handlePositionDataChange(allPositions.value[index], index)
    }
  })
}

// 防止重复弹窗的记录
const lastErrorMessage = ref('')
const lastErrorTime = ref(0)

// 在表格中验证岗位名称
const validatePositionNameInTable = (row: TablePositionItem, index: number) => {
  console.log(`[验证岗位名称] 开始验证岗位: ${row.name}, isNew: ${row.isNew}, index: ${index}`)

  const name = row.name.trim()

  // 检查是否为空
  if (!name) {
    row.nameError = '岗位名称不能为空'
    console.log(`[验证岗位名称] 岗位名称为空`)
    return false
  }

  // 只对新增岗位进行重复性检查
  if (row.isNew) {
    console.log(`[验证岗位名称] 这是新增岗位，开始重复性检查`)

    // 应用岗位名称联动逻辑：如果不以"工"结尾，则添加"工"
    const finalPositionName = name.endsWith('工') ? name : name + '工'
    console.log(`[验证岗位名称] 最终岗位名称: ${finalPositionName}`)

    // 检查是否与其他岗位重名（需要考虑联动后的最终名称）
    const otherPositions = allPositions.value.filter((_, i) => i !== index && !_.isDeleted)
    console.log(`[验证岗位名称] 其他岗位数量: ${otherPositions.length}`)

    // 获取所有其他岗位的最终名称（应用联动逻辑）
    const existingFinalNames = otherPositions
      .map((p) => {
        const otherName = p.name.trim()
        if (!otherName) return ''
        const finalName = otherName.endsWith('工') ? otherName : otherName + '工'
        console.log(`[验证岗位名称] 其他岗位: ${otherName} -> ${finalName}`)
        return finalName
      })
      .filter((n) => n)

    // 同时还要检查已有岗位（在各个车间中的现有岗位）
    const existingPositionsInWorkshops: string[] = []
    tabList.value.forEach((workshop) => {
      if (workshop.positions) {
        workshop.positions.forEach((pos) => {
          if (pos.name && pos.name.trim()) {
            existingPositionsInWorkshops.push(pos.name.trim())
            console.log(`[验证岗位名称] 车间中已有岗位: ${pos.name}`)
          }
        })
      }
    })

    // 合并所有已存在的岗位名称
    const allExistingNames = [...existingFinalNames, ...existingPositionsInWorkshops]
    console.log(`[验证岗位名称] 所有已存在的岗位名称:`, allExistingNames)

    if (allExistingNames.includes(finalPositionName)) {
      const errorMessage = `岗位名称重复（保存后将变为"${finalPositionName}"）`
      row.nameError = errorMessage
      console.log(`[验证岗位名称] 发现重复: ${finalPositionName}`)
      console.log(`[验证岗位名称] 设置错误信息到岗位:`, row.id, row.nameError)

      // 防止重复弹窗：只有当错误消息不同，或者距离上次弹窗超过3秒时才弹窗
      const now = Date.now()
      if (lastErrorMessage.value !== errorMessage || now - lastErrorTime.value > 3000) {
        ElMessage.error(errorMessage)
        lastErrorMessage.value = errorMessage
        lastErrorTime.value = now
      }

      return false
    }
  } else {
    console.log(`[验证岗位名称] 这是已有岗位，跳过重复性检查`)
  }

  row.nameError = ''
  console.log(`[验证岗位名称] 验证通过`)

  // 清除错误记录
  if (lastErrorMessage.value) {
    lastErrorMessage.value = ''
  }

  // 由于现在直接修改的是 allPositions 中的对象引用，
  // 修改会自动反映到底层数据源，不需要额外的同步

  return true
}

// 处理岗位名称变化
const handlePositionNameChange = (position: TablePositionItem, index: number) => {
  console.log('[岗位名称变化]', { position: position.name, index })

  // 验证名称
  validatePositionNameInTable(position, index)

  // 弹窗中的联动：岗位名称变化时，工作地点自动更新为"岗位名称位"
  // 对所有岗位（新增和编辑）都应用联动
  // if (position.workplaceData?.length) {
  //   position.workplaceData.forEach((workplaceRow, wpIndex) => {
  //     const newWorkplace = `${position.name}位`
  //     console.log(`[岗位名称联动] 工作地点${wpIndex}: ${workplaceRow.workplace} -> ${newWorkplace}`)
  //     workplaceRow.workplace = newWorkplace
  //   })
  // }
}

// 岗位名称联动
const handlePositionNameChangeWithLinkage = (position: any, oldName: string, newName: string) => {
  console.log(`[岗位名称联动] 开始处理岗位名称变化: "${oldName}" -> "${newName}"`)

  if (!position?.tableData) {
    console.log(`[岗位名称联动] 位置数据不存在或无表格数据`)
    return
  }

  position.tableData.forEach((row: any, rowIndex: number) => {
    console.log(`[岗位名称联动] 处理第${rowIndex + 1}行数据:`, {
      原工作地点: row.testItem,
      危害数量: row.hazards?.length || 0
    })

    // 工作地点 = 岗位去掉后面的"工" + "工位"
    const newWorkplace = newName.replace(/工$/, '') + '工位'
    const oldWorkplace = row.testItem
    row.testItem = newWorkplace
    console.log(`[岗位名称联动] 工作地点更新: "${oldWorkplace}" -> "${newWorkplace}"`)

    if (row.hazards?.length) {
      // 收集所有危害名称，生成统一的来源
      const hazardNames = row.hazards.map((h: any) => h.cnName).join('、')
      // 工作地点去掉"工位"作为基础值
      const baseValue = newWorkplace.replace(/工位$/, '')
      const unifiedSource = `${baseValue}时产生${hazardNames}`
      console.log(`[岗位名称联动] 基础值: "${baseValue}", 统一来源: "${unifiedSource}"`)

      row.hazards.forEach((hazard: any, hazardIndex: number) => {
        // 接触时机 = 工作地点去掉后面的"工位" + "时"
        const contactTimingValue = baseValue + '时'
        const oldContactTiming = hazard.contactTiming
        hazard.contactTiming = contactTimingValue
        console.log(
          `[岗位名称联动] 危害${hazardIndex + 1}(${hazard.cnName}) 接触时机: "${oldContactTiming}" -> "${contactTimingValue}"`
        )

        // 工作内容 = 工作地点去掉后面的"工位" + "工作"
        const workContentValue = baseValue + '工作'
        const oldWorkContent = hazard.workContent
        hazard.workContent = workContentValue
        console.log(
          `[岗位名称联动] 危害${hazardIndex + 1}(${hazard.cnName}) 工作内容: "${oldWorkContent}" -> "${workContentValue}"`
        )

        // 所有危害使用统一的来源
        const oldSource = hazard.source
        hazard.source = hazard.source || row.source || unifiedSource
        console.log(
          `[岗位名称联动] 危害${hazardIndex + 1}(${hazard.cnName}) 来源: "${oldSource}" -> "${unifiedSource}"`
        )
      })
    } else {
      console.log(`[岗位名称联动] 第${rowIndex + 1}行无危害数据，跳过危害联动`)
    }
  })

  console.log(`[岗位名称联动] 岗位名称联动完成，共处理${position.tableData.length}行数据`)
  position.tableData = [...position.tableData]
  forceRefresh()
  setTimeout(() => surveyStore.printSurveyData(), 200)
}

// 工作地点联动
const handleWorkplaceChangeWithLinkage = (row: any, oldWorkplace: string, newWorkplace: string) => {
  console.log(`[工作地点联动] 开始处理工作地点变化: "${oldWorkplace}" -> "${newWorkplace}"`)
  console.log(`[工作地点联动] 行数据:`, {
    危害数量: row.hazards?.length || 0,
    危害列表: row.hazards?.map((h: any) => h.cnName) || []
  })

  if (row.hazards?.length) {
    // 收集所有危害名称，生成统一的来源
    const hazardNames = row.hazards.map((h: any) => h.cnName).join('、')
    const baseValue = newWorkplace.replace(/工位$/, '')
    const unifiedSource = `${baseValue}时产生${hazardNames}`
    console.log(`[工作地点联动] 基础值: "${baseValue}", 统一来源: "${unifiedSource}"`)

    row.hazards.forEach((hazard: any, hazardIndex: number) => {
      // 接触时机 = 工作地点去掉后面的"工位" + "时"
      const contactTimingValue = baseValue + '时'
      const oldContactTiming = hazard.contactTiming
      hazard.contactTiming = contactTimingValue
      console.log(
        `[工作地点联动] 危害${hazardIndex + 1}(${hazard.cnName}) 接触时机: "${oldContactTiming}" -> "${contactTimingValue}"`
      )

      // 工作内容 = 工作地点去掉后面的"工位" + "工作"
      const workContentValue = baseValue + '工作'
      const oldWorkContent = hazard.workContent
      hazard.workContent = workContentValue
      console.log(
        `[工作地点联动] 危害${hazardIndex + 1}(${hazard.cnName}) 工作内容: "${oldWorkContent}" -> "${workContentValue}"`
      )

      // 所有危害使用统一的来源
      const oldSource = hazard.source
      hazard.source = hazard.source || row.source || unifiedSource
      console.log(
        `[工作地点联动] 危害${hazardIndex + 1}(${hazard.cnName}) 来源: "${oldSource}" -> "${unifiedSource}"`
      )
    })

    console.log(`[工作地点联动] 工作地点联动完成，处理了${row.hazards.length}个危害`)
  } else {
    console.log(`[工作地点联动] 无危害数据，跳过危害联动`)
  }

  forceRefresh()
  setTimeout(() => surveyStore.printSurveyData(), 200)
}

// 根据岗位名称查找实际的岗位数据
const findActualPositionByName = (positionName: string) => {
  for (const tab of tabList.value) {
    if (tab.positions && Array.isArray(tab.positions)) {
      const position = tab.positions.find((p) => p.name === positionName)
      if (position) {
        return position
      }
    }
  }
  return null
}

// 处理岗位数据变化
const handlePositionDataChange = (position: TablePositionItem, index: number) => {
  console.log('[岗位数据变化]', { position, index })

  // 由于现在 allPositions 直接引用可修改的对象，
  // 表单的修改会自动反映在界面上，不需要额外的同步逻辑
}

// 处理岗位类型变化
const handlePositionTypeChange = (position: TablePositionItem, index: number) => {
  console.log('[岗位类型变化]', { positionType: position.positionType, index })

  // 根据岗位类型自动设置接触类型
  let newWorkPosition = ''
  if (position.positionType === 1) {
    // 固定岗位 -> 稳定接触
    newWorkPosition = '稳定'

    // 如果从流动改为固定，且有多于1行的工作地点，禁止切换
    if (position.workplaceData && position.workplaceData.length > 1) {
      console.log(
        `[岗位类型变化] 固定作业类型只能有一个工作地点，当前有${position.workplaceData.length}个，禁止切换`
      )
      ElMessage.warning('固定岗位只能有一个工作地点，请删除多余的工作地点后再切换')

      // 恢复原来的值，阻止切换
      nextTick(() => {
        position.positionType = 2 // 恢复为流动岗位
        console.log(`[岗位类型变化] 已恢复岗位类型为: 流动(2)`)
      })
      return
    }
  } else if (position.positionType === 2) {
    // 流动岗位 -> 非稳定接触
    newWorkPosition = '非稳定'
  }

  if (newWorkPosition && newWorkPosition !== position.workPosition) {
    console.log('[岗位类型变化] 自动设置接触类型为:', newWorkPosition)
    // 使用updatePositionField确保响应式更新
    updatePositionField(position, index, 'workPosition', newWorkPosition)

    // 更新工作地点的接触频度数据
    if (position.workplaceData && position.workplaceData.length > 0) {
      position.workplaceData.forEach((workplace: any) => {
        // 确保接触频度对象存在
        if (!workplace.contactFrequency) {
          workplace.contactFrequency = {
            count: 1,
            duration: 1,
            interval: 1
          }
        }

        // 根据作业类型设置接触时间
        if (newWorkPosition === '稳定') {
          // 固定作业：接触时间 = 工作时间
          workplace.contactTime = parseFloat(position.workHours) || 8
        } else if (newWorkPosition === '非稳定') {
          // 流动作业：接触时间也默认为工作时间
          workplace.contactTime = parseFloat(position.workHours) || 8
        }
      })
    }
  }
}

// 验证岗位名称

// 取消岗位管理
const cancelPositionManagement = () => {
  console.log('[岗位管理] 取消操作，重置数据')

  // 重置编辑模式状态
  isEditMode.value = false
  editingPositionId.value = ''

  // 重置展开状态
  expandedPositions.value.clear()

  // 重置数据到初始状态，丢弃所有未确认的修改
  const currentTab = tabList.value.find((tab) => tab.id === activeTab.value)
  if (currentTab) {
    // 重新加载已有岗位（恢复到原始状态）
    existingPositions.value = currentTab.positions ? [...currentTab.positions] : []

    // 重新创建已有岗位的编辑副本
    existingPositionsForEdit.value = existingPositions.value.map((pos) => ({
      id: pos.id,
      name: pos.name,
      totalPeople: pos.totalPeople,
      shiftCount: pos.shiftCount,
      positionType: pos.workMode === '固定' ? 1 : 2,
      workDays: pos.workDays,
      workHours: pos.workHours,
      workPosition: pos.workPosition,
      shiftSystem: pos.shiftSystem,
      workStartTime: pos.workStartTime,
      workEndTime: pos.workEndTime,
      isNew: false,
      isDeleted: pos.isDeleted || false,
      nameError: '',
      // 重新加载已有的工作地点数据
      workplaceData: loadWorkplaceDataFromPosition(pos)
    }))

    // 重置新增岗位列表
    newPositions.value = []

    // 如果没有任何岗位，则自动添加一个空白行
    if (existingPositions.value.length === 0) {
      newPositions.value = [
        {
          name: '',
          totalPeople: 1,
          shiftCount: 1,
          positionType: 1,
          workDays: defaultWorkDays.value,
          workHours: defaultWorkHours.value,
          workPosition: '稳定',
          shiftSystem: '一班',
          workStartTime:
            defaultWorkTimeSegments.value.length > 0
              ? defaultWorkTimeSegments.value[0].startTime
              : '09:00',
          workEndTime:
            defaultWorkTimeSegments.value.length > 0
              ? defaultWorkTimeSegments.value[defaultWorkTimeSegments.value.length - 1].endTime
              : '17:00',
          workTimeSegments:
            defaultWorkTimeSegments.value.length > 0
              ? JSON.parse(JSON.stringify(defaultWorkTimeSegments.value))
              : [
                {
                  id: `segment_${uuidv4()}`,
                  startTime: '09:00',
                  endTime: '17:00',
                  duration: 8
                }
              ],
          nameError: ''
        }
      ]
    }

    // 重置待删除列表
    positionsToDelete.value = []
  }

  positionTypeDialogVisible.value = false
}

// 确认岗位管理
const confirmPositionManagement = () => {
  console.log('=== 确认岗位管理 ===')

  const currentTab = tabList.value.find((tab) => tab.id === activeTab.value)
  if (!currentTab) {
    ElMessage.error('未找到当前车间')
    return
  }

  // 处理在弹窗中删除的岗位：按名称从所有车间中移除
  const deletedNames = new Set<string>()
  try {
    positionsToDelete.value.forEach((n) => n && deletedNames.add(n))
  } catch {}
  try {
    allPositions.value.forEach((p) => {
      if (!p.isNew && (p as any).isDeleted) {
        if (p.name) deletedNames.add(p.name)
      }
    })
  } catch {}
  if (deletedNames.size > 0) {
    tabList.value.forEach((workshop) => {
      if (Array.isArray(workshop.positions)) {
        workshop.positions = workshop.positions.filter((pos: any) => !deletedNames.has(pos.name))
      }
    })
    positionsToDelete.value = []
  }

  // 过滤掉空白的岗位行（名称为空的岗位）
  const validPositions = allPositions.value.filter(
    (position) => position.name && position.name.trim()
  )

  console.log(
    `[岗位管理] 总岗位数: ${allPositions.value.length}, 有效岗位数: ${validPositions.length}`
  )
  console.log(
    `[岗位管理] 有效岗位:`,
    validPositions.map((p) => ({ name: p.name, isNew: p.isNew }))
  )

  // 检查是否至少有一条有效岗位
  if (validPositions.length === 0) {
    ElMessage.warning('至少需要添加一个岗位')
    return
  }

  // 验证所有有效岗位的名称
  let hasError = false
  validPositions.forEach((position, index) => {
    if (!validatePositionNameInTable(position, index)) {
      hasError = true
    }
  })

  if (hasError) {
    ElMessage.error('岗位名称重复了')
    return
  }

  // 确保 positions 数组已初始化
  if (!currentTab.positions) {
    currentTab.positions = []
  }

  let addedCount = 0
  let updatedCount = 0

  // 更新已有岗位的信息（只处理有效岗位）
  console.log(`[确认保存] 开始处理 ${validPositions.length} 个有效岗位`)
  validPositions.forEach((tablePos) => {
    console.log(
      `[确认保存] 处理岗位: ${tablePos.name}, isNew: ${tablePos.isNew}, id: ${tablePos.id}`
    )
    console.log(`[确认保存] 岗位 "${tablePos.name}" 的工作地点数据:`, tablePos.workplaceData)

    if (!tablePos.isNew && tablePos.id) {
      // 在所有车间中查找原始岗位，不仅仅是当前车间
      let originalPos: any = null
      let originalWorkshop: any = null

      tabList.value.forEach((workshop) => {
        if (workshop.positions && workshop.positions.length > 0) {
          const found = workshop.positions.find((p) => p.id === tablePos.id)
          if (found) {
            originalPos = found
            originalWorkshop = workshop
          }
        }
      })

      console.log(`[确认保存] 找到原始岗位:`, !!originalPos)
      if (originalPos) {
        console.log(`[确认保存] 原始岗位所在车间:`, originalWorkshop?.name)
      }

      if (originalPos) {
        const hasChanges =
          originalPos.name !== tablePos.name ||
          originalPos.totalPeople !== tablePos.totalPeople ||
          originalPos.shiftCount !== tablePos.shiftCount ||
          (originalPos.workMode === '固定' ? 1 : 2) !== tablePos.positionType ||
          originalPos.workDays !== tablePos.workDays ||
          originalPos.workHours !== tablePos.workHours ||
          originalPos.workPosition !== tablePos.workPosition ||
          originalPos.shiftSystem !== tablePos.shiftSystem ||
          originalPos.workStartTime !== tablePos.workStartTime ||
          originalPos.workEndTime !== tablePos.workEndTime

        console.log(`[确认保存] 岗位 "${tablePos.name}" 是否有变化: ${hasChanges}`)

        if (hasChanges) {
          originalPos.name = tablePos.name
          originalPos.totalPeople = tablePos.totalPeople
          originalPos.shiftCount = tablePos.shiftCount
          originalPos.workMode = tablePos.positionType === 1 ? '固定' : '流动'
          originalPos.workPosition = tablePos.workPosition
          originalPos.workDays = tablePos.workDays
          originalPos.workHours = tablePos.workHours
          originalPos.shiftSystem = tablePos.shiftSystem
          originalPos.workStartTime = tablePos.workStartTime
          originalPos.workEndTime = tablePos.workEndTime

          updatedCount++
        }

        // 无论岗位信息是否有变化，都要同步工作地点数据
        console.log(`[确认保存] 检查岗位 "${tablePos.name}" 的工作地点数据:`, {
          hasWorkplaceData: !!tablePos.workplaceData,
          workplaceDataLength: tablePos.workplaceData?.length || 0,
          workplaceData: tablePos.workplaceData
        })

        if (tablePos.workplaceData && tablePos.workplaceData.length > 0) {
          console.log(`[确认保存] 开始同步岗位 "${tablePos.name}" 的工作地点数据`)
          syncWorkplaceDataToWorkshops(tablePos.name, tablePos.workplaceData)
        } else {
          console.log(`[确认保存] 岗位 "${tablePos.name}" 没有工作地点数据需要同步`)
        }
      }
    }
  })

  // 添加新岗位（从已过滤的有效岗位中筛选新岗位）
  const validNewPositions = validPositions.filter((pos) => pos.isNew)
  console.log(`[确认保存] 开始处理 ${validNewPositions.length} 个新增岗位`)
  validNewPositions.forEach((newPos, index) => {
    console.log(`[确认保存-新增] 处理新增岗位: ${newPos.name}`)
    console.log(`[确认保存-新增] 新增岗位 "${newPos.name}" 的工作地点数据:`, newPos.workplaceData)
    let positionName = newPos.name.trim()

    // 如果岗位名称最后一个字不是"工"，则添加"工"
    if (!positionName.endsWith('工')) {
      positionName = positionName + '工'
    }

    const workMode = newPos.positionType === 1 ? '固定' : '流动'

    const newPosition = {
      ...generateEmptyPosition(activeTab.value, currentTab.positions.length + index, positionName),
      totalPeople: newPos.totalPeople,
      shiftCount: newPos.shiftCount,
      operationType: props.operationType,
      workMode: workMode,
      workPosition: newPos.workPosition,
      workDays: newPos.workDays,
      workHours: newPos.workHours,
      shiftSystem: newPos.shiftSystem,
      workStartTime: newPos.workStartTime,
      workEndTime: newPos.workEndTime
    }

    newPosition.tableData = generateMockData(activeTab.value, newPosition.id, positionName)

    // 确保初始表格数据包含所有需要的属性
    newPosition.tableData.forEach((row) => {
      row.hazards = row.hazards || []
    })

    // 先将岗位添加到当前车间
    currentTab.positions.push(newPosition)
    addedCount++

    // 同步工作地点数据到对应的车间岗位
    console.log(`[确认保存-新增] 检查新增岗位 "${newPosition.name}" 的工作地点数据:`, {
      hasWorkplaceData: !!newPos.workplaceData,
      workplaceDataLength: newPos.workplaceData?.length || 0,
      workplaceData: newPos.workplaceData
    })

    if (newPos.workplaceData && newPos.workplaceData.length > 0) {
      console.log(`[确认保存-新增] 开始同步新增岗位 "${newPosition.name}" 的工作地点数据`)
      syncWorkplaceDataToWorkshops(newPosition.name, newPos.workplaceData)
    } else {
      console.log(`[确认保存-新增] 新增岗位 "${newPosition.name}" 没有工作地点数据需要同步`)
    }
  })

  // 统计所有岗位的工作地点数据
  let totalWorkplaceCount = 0
  validPositions.forEach((position) => {
    if (position.workplaceData) {
      const validWorkplaces = position.workplaceData.filter(
        (row) => row.workshop && row.workplace && row.workplace.trim()
      )
      totalWorkplaceCount += validWorkplaces.length
    }
  })

  // 强制刷新表格
  refreshAllTables()

  // 重置编辑模式状态
  isEditMode.value = false
  editingPositionId.value = ''

  // 重置展开状态
  expandedPositions.value.clear()

  positionTypeDialogVisible.value = false
  ElMessage.success(
    `岗位管理完成！新增 ${addedCount} 个岗位，更新 ${updatedCount} 个岗位${totalWorkplaceCount > 0 ? `，保存 ${totalWorkplaceCount} 条工作地点` : ''}`
  )
}

// 添加新的 ref 变量
const workshopDialogVisible = ref(false)

// 添加确认新增车间的函数
const confirmAddWorkshop = () => {
  console.log('=== 确认添加车间workshopList ===', JSON.stringify(workshopList.value))

  // 过滤掉空名称的车间行
  const validWorkshops = workshopList.value.filter((w) => w.name.trim())

  if (validWorkshops.length === 0) {
    ElMessage.warning('请至少输入一个车间名称')
    return
  }

  // 校验
  const names = validWorkshops.map((w) => w.name.trim())
  // 重名校验
  const nameSet = new Set()
  for (const n of names) {
    if (nameSet.has(n)) {
      ElMessage.warning('车间名称不能重复')
      return
    }
    nameSet.add(n)
  }
  console.log('添加的车间:', names)

  // 保留现有的车间数据
  const existingTabs = [...tabList.value]
  const updatedTabs: TabItem[] = []

  // 处理每个有效车间
  for (const item of validWorkshops) {
    // 检查是否已存在相同ID的车间
    const existingTab = existingTabs.find((tab) => tab.id === item.id)
    if (existingTab) {
      // 如果已存在，保留原有数据，只更新名称
      updatedTabs.push({
        ...existingTab,
        name: item.name,
        editingName: item.name
      })
    } else {
      // 如果是新车间，创建新的车间对象
      updatedTabs.push({
        id: item.id || generateId(),
        name: item.name,
        isEditing: false,
        editingName: item.name,
        projectId: String(route.query.projectId || ''),
        positions: []
      })
    }
  }

  // 更新store中的车间列表
  surveyStore.updateTabList(updatedTabs)

  // 如果当前没有激活的车间，设置为第一个车间
  if (!activeTab.value || !updatedTabs.find((tab) => tab.id === activeTab.value)) {
    surveyStore.updateActiveTab(updatedTabs[0]?.id || '')
  }

  workshopDialogVisible.value = false
  ElMessage.success('车间保存成功')
}

// 添加新的 ref 变量
const editWorkshopDialogVisible = ref(false)
const editingWorkshop = ref<TabItem | null>(null)
const editingWorkshopName = ref('')

// 添加确认修改车间名称的函数
const confirmEditWorkshop = () => {
  if (!editingWorkshop.value) return

  if (!editingWorkshopName.value.trim()) {
    ElMessage.warning('请输入车间名称')
    return
  }

  const isDuplicate = tabList.value.some(
    (tab) => tab.id !== editingWorkshop.value?.id && tab.name === editingWorkshopName.value.trim()
  )
  if (isDuplicate) {
    ElMessage.warning('车间名称已存在')
    return
  }

  const updatedTabs = tabList.value.map((tab) => {
    if (tab.id === editingWorkshop.value?.id) {
      return {
        ...tab,
        name: editingWorkshopName.value.trim(),
        editingName: editingWorkshopName.value.trim()
      }
    }
    return tab
  })

  surveyStore.updateTabList(updatedTabs)

  editWorkshopDialogVisible.value = false
  editingWorkshop.value = null
  editingWorkshopName.value = ''

  ElMessage.success('车间名称修改成功')
}

// [修改] 查找包含指定行的岗位 (支持跨车间全局查找)
const findPositionByRow = (row: any) => {
  // 遍历所有车间，不仅仅是当前激活的车间
  for (const tab of tabList.value) {
    if (tab.positions && Array.isArray(tab.positions)) {
      for (const pos of tab.positions) {
        // 检查该岗位的 tableData 中是否包含目标行
        // 兼容 id 和 originalId (展开行情况)
        const found = pos.tableData.some((item) =>
          item.id === row.id ||
          item.id === row.originalId ||
          (item.originalId && item.originalId === row.id)
        );

        if (found) {
          return pos; // 找到了，返回该岗位对象
        }
      }
    }
  }
  console.warn('[查找岗位] 未能在任何车间找到包含该行的岗位', row);
  return null;
}

// 打开危害识别弹窗
const openHazardIdentification = async (row: TableItem) => {
  console.log('=== 打开危害识别弹窗 ===')
  if (!row) {
    ElMessage.error('数据错误，请重试')
    return
  }

  // 获取岗位名称
  const position = findPositionByRow(row)
  const positionName = position?.name || ''
  console.log('获取到的岗位名称:', positionName)

  currentRow.value = row as any
  currentPositionName.value = positionName
  // 直接传递数据给 open 方法
  await hazardIdentificationRef.value?.open(row)
}

// 监听表格数据变化
watch(
  () =>
    tabList.value.map((tab) =>
      tab.positions.map((pos) =>
        pos.tableData.map((row) => ({
          sampleDays: row.sampleDays,
          sampleCount: row.sampleCount,
          backupCount: row.backupCount,
          flowRate: row.flowRate,
          sampleDuration: row.sampleDuration,
          sampleMethod: row.sampleMethod,
          longShortTime: row.longShortTime
        }))
      )
    ),
  () => {
    // console.log('=== 采样数据发生变化，准备保存 ===')
    surveyStore.printSurveyData()
  },
  { deep: true }
)

// [修改] 删除处理方法 (支持跨车间)
const handleDelete = (row: TableItem) => { // 移除 tab 参数
  console.log('准备删除行:', row)

  // 1. 全局查找该行所属的岗位和车间
  let targetPosition: any = null;
  let targetTab: any = null;
  let targetRowIndex = -1;

  // 遍历所有车间寻找目标
  for (const tab of tabList.value) {
    if (tab.positions) {
      for (const pos of tab.positions) {
        const idx = pos.tableData.findIndex((r) => r.id === row.id);
        if (idx !== -1) {
          targetPosition = pos;
          targetTab = tab;
          targetRowIndex = idx;
          break;
        }
      }
    }
    if (targetPosition) break;
  }

  if (!targetPosition || !targetTab) {
    ElMessage.error('删除失败：未找到该行所属的岗位或车间')
    return;
  }

  // 2. 执行删除
  ElMessageBox.confirm('确认删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (props.operationType == 1) {
      // 调查模式：物理删除
      targetPosition.tableData.splice(targetRowIndex, 1)

      // 如果岗位空了，是否删除岗位？(保持你原有逻辑)
      if (targetPosition.tableData.length === 0) {
        const posIdx = targetTab.positions.indexOf(targetPosition);
        if (posIdx > -1) targetTab.positions.splice(posIdx, 1);
      }
    } else {
      // 方案模式：物理删除 (你的代码逻辑是这样)
      targetPosition.tableData.splice(targetRowIndex, 1)
      if (targetPosition.tableData.length === 0) {
        const posIdx = targetTab.positions.indexOf(targetPosition);
        if (posIdx > -1) targetTab.positions.splice(posIdx, 1);
      }
    }

    // 强制刷新视图 (因为修改的是深层数据)
    targetTab.positions = [...targetTab.positions]

    // 触发计算属性重新计算
    forceRefresh()

    ElMessage.success('删除成功')
    surveyStore.printSurveyData()

    // [重要] 如果删除的是跨车间行，还需要触发接触时间同步
    syncContactTimeToLaborers(targetPosition);
  })
    .catch(() => {})
}

// 岗位管理弹窗中，表单右上角删除岗位
const onDeletePositionInForm = (position: TablePositionItem, index: number) => {
  ElMessageBox.confirm('确定要删除该岗位吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (position?.isNew) {
        const newCount = newPositions.value.length
        if (index >= 0 && index < newCount) {
          newPositions.value.splice(index, 1)
        } else {
          const i = newPositions.value.findIndex((p) => p.id === position.id)
          if (i > -1) newPositions.value.splice(i, 1)
        }
      } else {
        const newCount = newPositions.value.length
        const actualIndex = index - newCount
        if (actualIndex >= 0 && actualIndex < existingPositionsForEdit.value.length) {
          const name = existingPositionsForEdit.value[actualIndex]?.name
          if (name && !positionsToDelete.value.includes(name)) {
            positionsToDelete.value.push(name)
          }
          existingPositionsForEdit.value.splice(actualIndex, 1)
        } else {
          const actualIdx = existingPositionsForEdit.value.findIndex((p) => p.id === position.id)
          if (actualIdx > -1) {
            const name = existingPositionsForEdit.value[actualIdx]?.name
            if (name && !positionsToDelete.value.includes(name)) {
              positionsToDelete.value.push(name)
            }
            existingPositionsForEdit.value.splice(actualIdx, 1)
          }
        }
      }
      if (editingPositionId.value === position?.id) {
        editingPositionId.value = ''
      }
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

const editPosition = (position: any) => {
  // 使用岗位管理弹窗进行编辑，传入岗位ID
  handleAddPosition(activeTab.value, position.id)
}
const editPositionName = (position: any) => {
  editingPositionData.value = position
  editingPositionName.value = position.name
  editPositionDialogVisible.value = true
}

const confirmEditPosition = () => {
  console.log(`[确认修改岗位] 开始处理岗位名称修改`)
  const newName = editingPositionName.value.trim()
  console.log(`[确认修改岗位] 新岗位名称: "${newName}"`)

  if (!newName) {
    console.log(`[确认修改岗位] 岗位名称为空，操作终止`)
    ElMessage.warning('岗位名称不能为空')
    return
  }

  // 校验重名（同车间下）
  const currentTab = tabList.value.find((tab) => tab.id === activeTab.value)
  console.log(`[确认修改岗位] 当前车间:`, currentTab ? currentTab.name : '未找到')
  console.log(`[确认修改岗位] 编辑的岗位:`, {
    id: editingPositionData.value?.id,
    oldName: editingPositionData.value?.name,
    tableDataLength: editingPositionData.value?.tableData?.length || 0
  })

  if (
    currentTab &&
    currentTab.positions.some((p) => p.id !== editingPositionData.value.id && p.name === newName)
  ) {
    console.log(`[确认修改岗位] 岗位名称"${newName}"已存在，操作终止`)
    ElMessage.warning('岗位名称已存在')
    return
  }

  const oldName = editingPositionData.value.name
  editingPositionData.value.name = newName
  console.log(`[确认修改岗位] 岗位名称已更新: "${oldName}" -> "${newName}"`)

  // 岗位名称变化时的联动逻辑：更新工作地点、接触时机、工作内容、来源
  console.log(`[确认修改岗位] 开始调用联动逻辑`)
  // handlePositionNameChangeWithLinkage(editingPositionData.value, oldName, newName)
  console.log(`[确认修改岗位] 联动逻辑调用完成`)

  editPositionDialogVisible.value = false
  ElMessage.success('岗位名称修改成功')
  console.log(`[确认修改岗位] 岗位名称修改流程完成`)
}

const copePosition = (position: any) => {
  // 获取当前车间
  const currentTab = tabList.value.find((tab) => tab.id === activeTab.value)
  if (!currentTab) {
    ElMessage.error('未找到当前车间')
    return
  }
  // 深拷贝岗位
  const newPosition = JSON.parse(JSON.stringify(position))
  // 生成新ID
  newPosition.id = `position_${uuidv4()}`
  // 岗位名称自动加后缀，避免重名
  let baseName = position.name.replace(/(\(复制\d*\))?$/, '')
  let copyIndex = 1
  let newName = `${baseName}(复制)`
  const existNames = currentTab.positions.map((p) => p.name)
  while (existNames.includes(newName)) {
    copyIndex++
    newName = `${baseName}(复制${copyIndex})`
  }
  newPosition.name = newName
  // tableData 也要全部生成新 id
  if (Array.isArray(newPosition.tableData)) {
    newPosition.tableData = newPosition.tableData.map((row) => ({
      ...row,
      id: `${row.id}_copy_${uuidv4()}`,
      rowKey: `${row.rowKey}_copy_${uuidv4()}`
    }))
  }
  // 插入到当前车间岗位列表
  currentTab.positions.push(newPosition)
  ElMessage.success('岗位复制成功')
}


// === 通用重算方法 ===
const recalculateRowHazards = async (row: any) => {
  if (!row || !row.hazards || row.hazards.length === 0) return

  // 1. 锁定当前行上下文（handleHazardUpdate 依赖 currentRow）
  currentRow.value = row

  // 2. 提取“根”危害（去重）
  // 现状：hazards 可能包含之前拆分的 TWA/STEL，如果不去重，会导致重复计算或死循环
  const uniqueMap = new Map<string, any>()

  row.hazards.forEach((h: any) => {
    const key = String(h.id)

    // 仅处理尚未加入的危害
    if (!uniqueMap.has(key)) {
      // 创建副本
      const cleanHazard = { ...h }

      // 【关键】清除所有由拆分逻辑产生的临时标记
      // 这样 handleHazardUpdate 就会把它当做一条“新”危害重新根据规则生成 TWA/STEL
      delete cleanHazard.__forcedBySplit
      delete cleanHazard.__forceTimeType
      delete cleanHazard.__forceStrengthType
      delete cleanHazard.__skipLaborerSync

      uniqueMap.set(key, cleanHazard)
    }
  })

  const baseHazards = Array.from(uniqueMap.values())

  console.log(`[触发重算] 行：${row.testItem}，去重后危害数：${baseHazards.length}`)

  // 3. 调用核心逻辑
  await handleHazardUpdate(baseHazards)
}

const handleHazardUpdate = async (hazards: Hazard[]) => {
  console.log('🚀 === [DEBUG-FIX] 危害更新逻辑开始 ===')
  console.log('📥 输入危害数据:', {
    hazardsCount: hazards?.length,
    hazards: hazards.map(h => ({ id: h.id, name: h.cnName, type: h.type }))
  })

  if (!currentRow.value) {
    console.warn('⚠️ 当前行为空，终止危害更新')
    return
  }

  console.log('📍 当前行信息:', currentRow.value)
  const position = findPositionByRow(currentRow.value)
  if (!position) {
    console.error('❌ 无法找到对应岗位信息')
    return
  }

  console.log('✅ 找到岗位信息:', { positionId: position.id, workMode: position.workMode })
  const originalRowId = currentRow.value.originalId
  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) {
    console.error('❌ 无法找到原始行数据', { originalRowId })
    return
  }

  console.log('🎯 原始行数据:', {
    workLocation: originalRow.workLocation,
    testItem: originalRow.testItem,
    contactTime: originalRow.contactTime,
    existingHazardsCount: originalRow.hazards?.length || 0
  })

  // 清空处理
  if (hazards.length === 0) {
    console.log('🔄 危害列表为空，执行清空操作')
    originalRow.hazards = []
    if (originalRow.workLocation === 1) {
      console.log('🏭 工位行清空，同步清空劳动者行危害')
      const targetRows = position.tableData.filter((item) => item.workLocation === 2)
      targetRows.forEach((targetRow) => {
        console.log(`🧹 清空劳动者行危害:`, targetRow.id)
        targetRow.hazards = []
      })
    }
    position.tableData = [...position.tableData]
    console.log('✅ 清空操作完成')
    return
  }

  // ---------------------------------------------------------------
  // 1. 预处理与元数据补全 (Metadata Hydration)
  // ---------------------------------------------------------------
  console.log('🔧 开始预处理与元数据补全...')
  const oldHazards = originalRow.hazards || []
  const hazardNames = getUniqueHazardsByName(hazards as any[]).map((h: any) => h.cnName).join('、')
  const workContent = originalRow.testItem?.replace(/工位$/, '') || ''
  const unifiedSource = `${workContent}时产生${hazardNames}`
  const contactTimingValue = workContent.replace(/工位$/, '') + '时'

  console.log('📋 预处理信息:', {
    hazardNames,
    workContent,
    unifiedSource,
    contactTimingValue,
    oldHazardsCount: oldHazards.length
  })

  for (const [index, hazard] of hazards.entries()) {
    console.log(`🔍 处理危害 [${index + 1}/${hazards.length}]:`, {
      id: hazard.id,
      name: hazard.cnName,
      type: hazard.type,
      currentOperationType: hazard.operationType
    })

    // 继承 operationType
    if (hazard.operationType === undefined || hazard.operationType === null) {
      const oldSame = oldHazards.find((h) => h.cnName === hazard.cnName && h.operationType != null)
      hazard.operationType = oldSame ? oldSame.operationType : props.operationType
      console.log(`🔄 设置operationType:`, { from: oldSame ? 'existing' : 'props', value: hazard.operationType })
    }

    // 【关键修复】：检查并补全丢失的元数据 (longTimeFlow, pcTwa 等)
    const asAny = hazard as any
    const missingMeta = asAny.longTimeFlow === undefined && asAny.long_time_flow === undefined

    if ((missingMeta || !hazard.type) && hazard.id) {
      console.log(`⚠️ 危害 ${hazard.cnName} 缺少元数据，正在重新获取...`, {
        missingMeta,
        hasType: !!hazard.type,
        id: hazard.id
      })
      await fetchHazardInfo(hazard)
      console.log(`✅ 危害元数据获取完成:`, {
        longTimeFlow: asAny.longTimeFlow,
        pcTwa: asAny.pcTwa,
        type: hazard.type
      })
    }

    // 基础字段赋值
    hazard.workContent = workContent + '工作'
    hazard.contactTiming = contactTimingValue
    hazard.source = hazard.source || originalRow.source || unifiedSource
    hazard.worker = []
    if (!hazard.laborIntensity) hazard.laborIntensity = 'I'

    if (hazard.sampling) {
      const sampleType = originalRow.workLocation === 1 ? 'fix' : 'personal'
      hazard.sampling.sampleType = sampleType
      if (hazard.sampling.isCustomTime === undefined) hazard.sampling.isCustomTime = false
      console.log(`⚙️ 设置采样信息:`, { sampleType, isCustomTime: hazard.sampling.isCustomTime })
    }

    console.log(`✅ 危害预处理完成:`, {
      workContent: hazard.workContent,
      contactTiming: hazard.contactTiming,
      source: hazard.source,
      laborIntensity: hazard.laborIntensity
    })
  }

  const isNumeric = (v: any) => {
    const s = (v ?? '').toString().trim()
    return s !== '' && /^-?\d+(\.\d+)?$/.test(s)
  }

  // ---------------------------------------------------------------
  // 2. 核心拆分逻辑 (Station Row Splitting)
  // ---------------------------------------------------------------
  console.log('🔄 开始核心拆分逻辑...')
  try {
    const isFixedWorkMode = (position?.workMode || '') === '固定'
    const ctVal = typeof originalRow.contactTime === 'string'
      ? parseFloat(originalRow.contactTime || '0')
      : originalRow.contactTime || 0

    console.log(`📊 拆分判断参数:`, {
      workMode: position.workMode,
      isFixedWorkMode,
      contactTime: ctVal,
      workLocation: originalRow.workLocation
    })

    // 场景 1: 固定岗位 >= 1h
    if (isFixedWorkMode && ctVal >= 1) {
      console.log(`🎯 进入固定岗位拆分逻辑 (接触时间 >= 1h)`)
      const expanded: any[] = []

      for (const [index, hz] of hazards.entries()) {
        console.log(`🔍 分析危害 [${index + 1}/${hazards.length}]:`, {
          name: hz.cnName,
          type: hz.type
        })

        const isChemType2 = String(hz?.type) === '2'
        const isPhysicalType3 = String(hz?.type) === '3'
        const hasPcTwa = isNumeric((hz as any)?.pcTwa ?? (hz as any)?.pc_twa)
        const hasPcStel = isNumeric((hz as any)?.pcStel ?? (hz as any)?.pc_stel)
        const hasLongFlow = isNumeric((hz as any)?.longTimeFlow ?? (hz as any)?.long_time_flow ?? (hz as any)?.long_time_flow1)
        const hasShortFlow = isNumeric((hz as any)?.shortTimeFlow ?? (hz as any)?.short_time_flow ?? (hz as any)?.short_time_flow1)

        console.log(`📋 危害属性检查:`, {
          isChemType2,
          isPhysicalType3,
          hasPcTwa,
          hasPcStel,
          hasLongFlow,
          hasShortFlow
        })

        // 物理因素 Type 3
        if (isPhysicalType3 && originalRow.workLocation === 1) {
          console.log(`🎵 物理因素类型3，进行长短时拆分`)
          const base = JSON.parse(JSON.stringify(hz))
          const ensureSampling = (obj: any) => {
            if (!obj.sampling) obj.sampling = {
              sampleDays: 1, pointCount: 1, sampleCount: 1, contactHours: ctVal,
              startDay: 1, timeType: 'long', sampleType: 'fix', isCustomTime: false,
              sampleDuration: 0, flowRate: 0, strengthType: 1
            }
          }

          // Long
          const longRecord = JSON.parse(JSON.stringify(base))
          ensureSampling(longRecord);
          longRecord.sampling.timeType = 'long';
          longRecord.sampling.strengthType = 1;
          longRecord.sampling.contactHours = ctVal
          ;(longRecord as any).__forcedBySplit = true;
          (longRecord as any).__forceTimeType = 'long';
          (longRecord as any).__forceStrengthType = 1
          expanded.push(longRecord)
          console.log(`✅ 添加长时记录:`, { timeType: 'long', strengthType: 1 })

          // Short
          const shortRecord = JSON.parse(JSON.stringify(base))
          ensureSampling(shortRecord);
          shortRecord.sampling.timeType = 'short';
          shortRecord.sampling.strengthType = 4;
          shortRecord.sampling.contactHours = ctVal
          ;(shortRecord as any).__forcedBySplit = true;
          (shortRecord as any).__forceTimeType = 'short';
          (shortRecord as any).__forceStrengthType = 4;
          (shortRecord as any).__skipLaborerSync = true
          expanded.push(shortRecord)
          console.log(`✅ 添加短时记录:`, { timeType: 'short', strengthType: 4 })
          continue
        }

        // 化学因素 Type 2
        if (isChemType2 && hasPcTwa && hasPcStel && hasLongFlow) {
          console.log(`🧪 化学因素类型2 (TWA+STEL+长流量)，进行TWA/STEL拆分`)
          // TWA
          const twaLong = JSON.parse(JSON.stringify(hz))
          if(!twaLong.sampling) twaLong.sampling = {
            sampleDays:1, pointCount:1, sampleCount:1, contactHours:ctVal,
            startDay:1, timeType:'long', sampleType:'fix', isCustomTime:false,
            sampleDuration:0, flowRate:0, strengthType:1
          }
          twaLong.sampling.timeType = 'long';
          twaLong.sampling.strengthType = 1;
          twaLong.sampling.flowRate = (hz as any).longTimeFlow || (hz as any).long_time_flow || twaLong.sampling.flowRate
          twaLong.sampling.contactHours = ctVal
          ;(twaLong as any).__forcedBySplit = true;
          (twaLong as any).__forceTimeType = 'long';
          (twaLong as any).__forceStrengthType = 1
          expanded.push(twaLong)
          console.log(`✅ 添加TWA长时记录:`, { timeType: 'long', strengthType: 1, flowRate: twaLong.sampling.flowRate })

          // STEL
          const stelShort = JSON.parse(JSON.stringify(hz))
          if(!stelShort.sampling) stelShort.sampling = { ...twaLong.sampling }
          stelShort.sampling.timeType = 'short';
          stelShort.sampling.strengthType = 2;
          stelShort.sampling.flowRate = (hz as any).shortTimeFlow || (hz as any).short_time_flow || (hz as any).longTimeFlow || (hz as any).long_time_flow || stelShort.sampling.flowRate
          stelShort.sampling.contactHours = ctVal
          ;(stelShort as any).__forcedBySplit = true;
          (stelShort as any).__forceTimeType = 'short';
          (stelShort as any).__forceStrengthType = 2
          expanded.push(stelShort)
          console.log(`✅ 添加STEL短时记录:`, { timeType: 'short', strengthType: 2, flowRate: stelShort.sampling.flowRate })
          continue
        }
        // 仅 TWA + LongFlow -> TWA + PE
        else if (isChemType2 && hasPcTwa && !hasPcStel && hasLongFlow) {
          console.log(`🧪 化学因素类型2 (仅TWA+长流量)，进行TWA/PE拆分`)
          const twaLong = JSON.parse(JSON.stringify(hz))
          if(!twaLong.sampling) twaLong.sampling = {
            sampleDays:1, pointCount:1, sampleCount:1, contactHours:ctVal,
            startDay:1, timeType:'long', sampleType:'fix', isCustomTime:false,
            sampleDuration:0, flowRate:0, strengthType:1
          }
          twaLong.sampling.timeType = 'long';
          twaLong.sampling.strengthType = 1;
          twaLong.sampling.flowRate = (hz as any).longTimeFlow || (hz as any).long_time_flow || twaLong.sampling.flowRate
          twaLong.sampling.contactHours = ctVal
          ;(twaLong as any).__forcedBySplit = true;
          (twaLong as any).__forceTimeType = 'long';
          (twaLong as any).__forceStrengthType = 1
          expanded.push(twaLong)
          console.log(`✅ 添加TWA长时记录:`, { timeType: 'long', strengthType: 1, flowRate: twaLong.sampling.flowRate })

          const peShort = JSON.parse(JSON.stringify(hz))
          if(!peShort.sampling) peShort.sampling = { ...twaLong.sampling }
          peShort.sampling.timeType = 'short';
          peShort.sampling.strengthType = 4;
          peShort.sampling.flowRate = (hz as any).shortTimeFlow || (hz as any).short_time_flow || (hz as any).longTimeFlow || (hz as any).long_time_flow || peShort.sampling.flowRate
          peShort.sampling.contactHours = ctVal
          ;(peShort as any).__forcedBySplit = true;
          (peShort as any).__forceTimeType = 'short';
          (peShort as any).__forceStrengthType = 4
          expanded.push(peShort)
          console.log(`✅ 添加PE短时记录:`, { timeType: 'short', strengthType: 4, flowRate: peShort.sampling.flowRate })
          continue
        }
        // 无长流量，有短流量 -> Short only
        else if (ctVal >= 1 && isChemType2 && hasPcTwa && hasShortFlow && !hasLongFlow) {
          console.log(`🧪 化学因素类型2 (无长流量，有短流量)，仅创建短时记录`)
          const base = JSON.parse(JSON.stringify(hz))
          const sType = hasPcStel ? 5 : 6
          if (!base.sampling) base.sampling = {
            sampleDays:1, pointCount:1, sampleCount:1, contactHours:ctVal,
            startDay:1, timeType:'short', sampleType:'fix', isCustomTime:false,
            sampleDuration:0, flowRate:0, strengthType:sType
          }
          else {
            base.sampling.timeType = 'short';
            base.sampling.strengthType = sType
          }
          base.sampling.flowRate = (hz as any).shortTimeFlow || (hz as any).short_time_flow || base.sampling.flowRate
          base.sampling.contactHours = ctVal
          ;(base as any).__forcedBySplit = true;
          (base as any).__forceTimeType = 'short';
          (base as any).__forceStrengthType = sType
          expanded.push(base)
          console.log(`✅ 添加短时记录:`, { timeType: 'short', strengthType: sType, flowRate: base.sampling.flowRate })
          continue
        }

        console.log(`ℹ️ 危害无需拆分，直接保留`)
        expanded.push(hz)
      }
      hazards = expanded
      console.log(`📈 固定岗位拆分完成:`, { before: hazards.length, after: expanded.length })
    }

    // 2. 流动岗位 >= 1h
    if (!isFixedWorkMode && (position?.workMode || '') === '流动' && ctVal >= 1) {
      console.log(`🎯 进入流动岗位拆分逻辑 (接触时间 >= 1h)`)
      const expandedFlow: any[] = []

      for (const [index, hz] of hazards.entries()) {
        console.log(`🔍 分析流动岗位危害 [${index + 1}/${hazards.length}]:`, {
          name: hz.cnName,
          type: hz.type
        })

        const typeStr = String(hz?.type)
        const isType2 = typeStr === '2'
        const isType3 = typeStr === '3'
        const hasPcTwa = isNumeric((hz as any)?.pcTwa ?? (hz as any)?.pc_twa)
        const hasPcStel = isNumeric((hz as any)?.pcStel ?? (hz as any)?.pc_stel)
        const hasLongFlow = isNumeric((hz as any)?.longTimeFlow ?? (hz as any)?.long_time_flow ?? (hz as any)?.long_time_flow1)
        const hasShortFlow = isNumeric((hz as any)?.shortTimeFlow ?? (hz as any)?.short_time_flow ?? (hz as any)?.short_time_flow1)

        console.log(`📋 流动岗位危害属性:`, {
          isType2, isType3, hasPcTwa, hasPcStel, hasLongFlow, hasShortFlow
        })

        if (isType3 && originalRow.workLocation === 1) {
          console.log(`🎵 流动岗位物理因素类型3，创建短时记录`)
          const base = JSON.parse(JSON.stringify(hz))
          if (!base.sampling) base.sampling = {
            sampleDays:1, pointCount:1, sampleCount:1, contactHours:ctVal,
            startDay:1, timeType:'short', sampleType:'fix', isCustomTime:false,
            sampleDuration:0, flowRate:0, strengthType:6
          }
          else base.sampling.contactHours = ctVal
          base.sampling.timeType = 'short';
          base.sampling.strengthType = 4;
          ;(base as any).__forcedBySplit = true;
          (base as any).__forceTimeType = 'short';
          (base as any).__forceStrengthType = 4;
          (base as any).__skipLaborerSync = true
          expandedFlow.push(base)
          console.log(`✅ 添加流动岗位物理因素记录:`, { timeType: 'short', strengthType: 4 })
          continue
        }

        // 流动场景: TWA + STEL + LongFlow -> 保留 Short (STEL)
        if (isType2 && hasPcTwa && hasPcStel && hasLongFlow) {
          console.log(`🧪 流动岗位化学因素 (TWA+STEL+长流量)，保留STEL短时记录`)
          const base = JSON.parse(JSON.stringify(hz))
          if (!base.sampling) base.sampling = {
            sampleDays:1, pointCount:1, sampleCount:1, contactHours:ctVal,
            startDay:1, timeType:'short', sampleType:'fix', isCustomTime:false,
            sampleDuration:0, flowRate:0, strengthType:2
          }
          base.sampling.timeType = 'short';
          base.sampling.strengthType = 2;
          base.sampling.flowRate = (hz as any).shortTimeFlow || (hz as any).short_time_flow || (hz as any).longTimeFlow || base.sampling.flowRate
          ;(base as any).__forcedBySplit = true;
          (base as any).__forceTimeType = 'short';
          (base as any).__forceStrengthType = 2
          expandedFlow.push(base)
          console.log(`✅ 添加流动岗位STEL记录:`, { timeType: 'short', strengthType: 2, flowRate: base.sampling.flowRate })
          continue
        }
        // 流动场景: TWA + LongFlow (无STEL) -> 保留 Short (PE)
        if (isType2 && hasPcTwa && !hasPcStel && hasLongFlow) {
          console.log(`🧪 流动岗位化学因素 (TWA+长流量，无STEL)，保留PE短时记录`)
          const base = JSON.parse(JSON.stringify(hz))
          if (!base.sampling) base.sampling = {
            sampleDays:1, pointCount:1, sampleCount:1, contactHours:ctVal,
            startDay:1, timeType:'short', sampleType:'fix', isCustomTime:false,
            sampleDuration:0, flowRate:0, strengthType:4
          }
          base.sampling.timeType = 'short';
          base.sampling.strengthType = 4;
          base.sampling.flowRate = (hz as any).shortTimeFlow || (hz as any).short_time_flow || (hz as any).longTimeFlow || base.sampling.flowRate
          ;(base as any).__forcedBySplit = true;
          (base as any).__forceTimeType = 'short';
          (base as any).__forceStrengthType = 4
          expandedFlow.push(base)
          console.log(`✅ 添加流动岗位PE记录:`, { timeType: 'short', strengthType: 4, flowRate: base.sampling.flowRate })
          continue
        }

        console.log(`ℹ️ 流动岗位危害无需特殊处理，直接保留`)
        expandedFlow.push(hz)
      }
      hazards = expandedFlow
      console.log(`📈 流动岗位拆分完成:`, { before: hazards.length, after: expandedFlow.length })
    }
  } catch (e) {
    console.error('💥 拆分逻辑异常', e)
  }

  // 3. 接触时间 < 1h
  console.log('⏱️ 检查接触时间 < 1h 的情况...')
  try {
    const ctShort = typeof originalRow.contactTime === 'string' ? parseFloat(originalRow.contactTime || '0') : originalRow.contactTime || 0
    console.log(`📊 短接触时间检查:`, { contactTime: ctShort, workLocation: originalRow.workLocation })

    if (ctShort < 1 && originalRow.workLocation === 1) {
      console.log(`🎯 进入短接触时间处理逻辑 (< 1h)`)
      const adjusted: any[] = []

      for (const [index, hz] of hazards.entries()) {
        console.log(`🔍 处理短接触时间危害 [${index + 1}/${hazards.length}]:`, {
          name: hz.cnName,
          type: hz.type
        })

        const typeStr = String(hz?.type)
        const hasPcTwa = isNumeric((hz as any)?.pcTwa ?? (hz as any)?.pc_twa)
        const hasPcStel = isNumeric((hz as any)?.pcStel ?? (hz as any)?.pc_stel)

        if (typeStr === '1') {
          (hz as any).__skipLaborerSync = true;
          adjusted.push(hz);
          console.log(`✅ 类型1危害，标记跳过劳动者同步`)
          continue
        }

        if ((typeStr === '2' && hasPcTwa) || typeStr === '3') {
          console.log(`🔄 类型2/3危害，调整为短时记录`)
          const base = JSON.parse(JSON.stringify(hz))
          const strengthType = (hasPcStel && typeStr==='2') ? 2 : 4
          if (!base.sampling) base.sampling = {
            sampleDays:1, pointCount:1, sampleCount:1, contactHours:ctShort,
            startDay:1, timeType:'short', sampleType:'fix', isCustomTime:false,
            sampleDuration:0, flowRate:0, strengthType
          }
          else {
            base.sampling.timeType = 'short';
            base.sampling.contactHours = ctShort;
            base.sampling.strengthType = strengthType
          }
          ;(base as any).__forcedBySplit = true;
          (base as any).__forceTimeType = 'short';
          (base as any).__forceStrengthType = strengthType;
          (base as any).__skipLaborerSync = true
          adjusted.push(base)
          console.log(`✅ 调整为短时记录:`, { timeType: 'short', strengthType, contactHours: ctShort })
          continue
        }

        console.log(`ℹ️ 危害无需调整，直接保留`)
        adjusted.push(hz)
      }
      hazards = adjusted

      // 清理 labor rows for <1h
      console.log(`🧹 清理劳动者行危害 (接触时间 < 1h)`)
      const laborerRows = position.tableData.filter((row: any) => row.workLocation === 2)
      laborerRows.forEach((row: any) => {
        const beforeCount = row.hazards?.length || 0
        if (row.hazards) {
          row.hazards = row.hazards.filter((h: any) => String(h?.type) !== '2' && String(h?.type) !== '3')
        }
        const afterCount = row.hazards?.length || 0
        console.log(`🧹 劳动者行清理:`, { rowId: row.id, before: beforeCount, after: afterCount })
      })

      console.log(`📈 短接触时间处理完成:`, { adjustedCount: adjusted.length })
    }
  } catch (e) {
    console.error('💥 短接触时间处理异常', e)
  }

  originalRow.hazards = hazards
  console.log(`✅ 危害数据设置到原始行:`, { hazardsCount: hazards.length })

  // ---------------------------------------------------------------
  // 3. 同步到劳动者 (Sync to Laborer)
  // ---------------------------------------------------------------
  console.log('👥 开始同步到劳动者行...')
  if (originalRow.workLocation === 1) {
    const targetRows = position.tableData.filter((item) => item.workLocation === 2)
    console.log(`📋 找到劳动者行:`, { count: targetRows.length, rows: targetRows.map(r => r.id) })

    if (targetRows.length > 0) {
      let hazardsCopy = JSON.parse(JSON.stringify(hazards))
      const ct2Val = typeof originalRow.contactTime === 'string' ? parseFloat(originalRow.contactTime || '0') : originalRow.contactTime || 0
      const extraForLaborer: any[] = []

      console.log(`📊 劳动者同步参数:`, {
        originalHazardsCount: hazards.length,
        contactTime: ct2Val,
        workMode: position.workMode
      })

      try {
        for (const [index, hz] of hazardsCopy.entries()) {
          console.log(`🔍 检查劳动者同步危害 [${index + 1}/${hazardsCopy.length}]:`, {
            name: hz.cnName,
            type: hz.type
          })

          const isChemType2 = String(hz?.type) === '2'
          const isPhysicalType3 = String(hz?.type) === '3'
          const hasPcTwa = isNumeric((hz as any)?.pcTwa ?? (hz as any)?.pc_twa)
          const hasLongFlow = isNumeric((hz as any)?.longTimeFlow ?? (hz as any)?.long_time_flow ?? (hz as any)?.long_time_flow1)

          console.log(`📋 劳动者同步检查:`, { isChemType2, isPhysicalType3, hasPcTwa, hasLongFlow })

          // 流动岗位：通常只有 Short 记录，需要为劳动者补充 Long 记录
          if ((position?.workMode || '') === '流动' && ct2Val >= 1) {
            if (isChemType2 && hasPcTwa && hasLongFlow) {
              console.log(`🔄 流动岗位化学因素，为劳动者补充长时记录`)
              const longForLab = {
                ...(JSON.parse(JSON.stringify(hz)) as any),
                sampling: { ...hz.sampling, timeType:'long', sampleType:'personal', strengthType:1, contactHours:ct2Val },
                __forcedBySplit:true,
                __forceTimeType:'long',
                __forceStrengthType:1,
                mac:''
              }
              extraForLaborer.push(longForLab)
              console.log(`✅ 补充劳动者长时记录:`, { timeType: 'long', strengthType: 1 })
            }
            if (isPhysicalType3) {
              console.log(`🔄 流动岗位物理因素，为劳动者补充长时记录`)
              const noiseLong = {
                ...(JSON.parse(JSON.stringify(hz)) as any),
                sampling: { ...hz.sampling, timeType:'long', sampleType:'personal', strengthType:1, contactHours:ct2Val },
                __forcedBySplit:true,
                __forceTimeType:'long',
                __forceStrengthType:1
              }
              delete (noiseLong as any).__skipLaborerSync
              extraForLaborer.push(noiseLong)
              console.log(`✅ 补充劳动者物理因素长时记录:`, { timeType: 'long', strengthType: 1 })
            }
          }
        }
      } catch(e) {
        console.error('💥 劳动者补充逻辑异常', e)
      }

      if (extraForLaborer.length) {
        hazardsCopy = hazardsCopy.concat(extraForLaborer)
        console.log(`📈 补充劳动者记录后:`, { before: hazardsCopy.length - extraForLaborer.length, after: hazardsCopy.length })
      }

      // 过滤
      console.log(`🔍 开始过滤劳动者危害...`)
      const beforeFilterCount = hazardsCopy.length
      hazardsCopy = hazardsCopy.filter((hz: any) => {
        const typeStr = String(hz?.type)
        const hazardName = hz?.cnName || '未知'

        // [NEW] 强校验：Type=2 必须有长时流量数值
        if (typeStr === '2') {
          const hasValidLongFlow = isNumeric(hz?.longTimeFlow ?? hz?.long_time_flow ?? hz?.long_time_flow1)
          if (!hasValidLongFlow) {
            console.log(`🚫 [同步过滤] ${hazardName} 缺少长时流量`)
            return false
          }
        }

        const isNoisePhysicalHazard = (h: any): boolean => {
          if (!h) return false
          if (String(h?.type) !== '1') return false
          return (h?.cnName ?? '').toString().includes('噪声')
        }

        if (typeStr === '1' && isNoisePhysicalHazard(hz)) {
          console.log(`✅ 保留噪声危害:`, hazardName)
          return true
        }
        if (typeStr === '1') {
          console.log(`🚫 过滤非噪声类型1危害:`, hazardName)
          return false
        }
        if ((hz as any)?.__skipLaborerSync) {
          console.log(`🚫 过滤标记跳过同步的危害:`, hazardName)
          return false
        }

        const isNumericMac = (v: any) => {
          const s = (v ?? '').toString().trim();
          return s !== '' && /^-?\d+(\.\d+)?$/.test(s)
        }
        if (typeStr === '2' && isNumericMac(hz?.mac)) {
          console.log(`🚫 过滤有数值MAC的类型2危害:`, hazardName)
          return false
        }

        // 过滤掉短时间记录 (STEL/PE)，劳动者只测长时间
        if (typeStr === '2' && isNumeric(hz?.longTimeFlow ?? hz?.long_time_flow)) {
          const tt = hz?.sampling?.timeType
          if (tt && tt !== 'long') {
            console.log(`🚫 过滤短时记录:`, { name: hazardName, timeType: tt })
            return false
          }
        }

        if ((position?.workMode || '') === '流动' && ct2Val >= 1) {
          const tt = hz?.sampling?.timeType
          if (tt && tt !== 'long') {
            console.log(`🚫 流动岗位过滤非长时记录:`, { name: hazardName, timeType: tt })
            return false
          }
        }

        console.log(`✅ 保留危害:`, hazardName)
        return true
      })

      console.log(`📊 劳动者危害过滤完成:`, { before: beforeFilterCount, after: hazardsCopy.length })

      // 赋值到劳动者行
      hazardsCopy.forEach((hazard) => {
        if (hazard.sampling) {
          hazard.sampling.sampleType = 'personal'
          console.log(`⚙️ 设置劳动者采样类型:`, { name: hazard.cnName, sampleType: 'personal' })
        }
        delete hazard.contactTime
      })

      targetRows.forEach((targetRow) => {
        console.log(`🔄 同步到劳动者行:`, targetRow.id)
        if (!targetRow.hazards) targetRow.hazards = []

        hazardsCopy.forEach((newHazard) => {
          const fullHazard = {
            ...newHazard,
            worker: newHazard.worker || [],
            contactTiming: newHazard.contactTiming || '',
            laborIntensity: newHazard.laborIntensity
          }
          const existIndex = targetRow.hazards.findIndex((h) => String(h.id) === String(fullHazard.id) && h.cnName === fullHazard.cnName)

          if (existIndex !== -1) {
            console.log(`🔄 更新现有劳动者危害:`, { name: fullHazard.cnName, row: targetRow.id })
            targetRow.hazards[existIndex] = { ...targetRow.hazards[existIndex], ...fullHazard }
          } else {
            const sameIdIndex = targetRow.hazards.findIndex((h) => String(h.id) === String(fullHazard.id))
            if (sameIdIndex !== -1) {
              console.log(`🔄 替换同ID劳动者危害:`, { name: fullHazard.cnName, row: targetRow.id })
              targetRow.hazards[sameIdIndex] = fullHazard
            } else {
              console.log(`✅ 新增劳动者危害:`, { name: fullHazard.cnName, row: targetRow.id })
              targetRow.hazards.push(fullHazard)
            }
          }
        })

        console.log(`📊 劳动者行同步完成:`, { row: targetRow.id, hazardsCount: targetRow.hazards.length })
      })

      syncContactTimeToLaborers(position)
      console.log(`✅ 接触时间同步完成`)
    } else {
      console.log(`ℹ️ 无劳动者行需要同步`)
    }
  } else {
    console.log(`ℹ️ 非工位行，跳过劳动者同步`)
  }

  // ---------------------------------------------------------------
  // 4. 后处理与初始化 (Initialization)
  // ---------------------------------------------------------------
  console.log('🔧 开始后处理与初始化...')
  position.tableData = [...position.tableData] // Trigger update before loops

  position.tableData.forEach((row, rowIndex) => {
    console.log(`🔍 处理行 [${rowIndex + 1}/${position.tableData.length}]:`, {
      id: row.id,
      workLocation: row.workLocation,
      hazardsCount: row.hazards?.length || 0
    })

    if (row.hazards && row.hazards.length > 0) {
      row.hazards.forEach((hazard, hazardIndex) => {
        console.log(`⚙️ 初始化危害 [${hazardIndex + 1}/${row.hazards.length}]:`, {
          name: hazard.cnName,
          type: hazard.type
        })

        if (hazard.sampling) {
          const forcedTime = (hazard as any).__forceTimeType
          const forcedStrength = (hazard as any).__forceStrengthType

          console.log(`📋 强制标记检查:`, { forcedTime, forcedStrength })

          if (forcedStrength == null) {
            const defaultStrength = getDefaultStrengthType(hazard)
            if (defaultStrength !== null && hazard.sampling.strengthType !== defaultStrength) {
              console.log(`🔄 设置默认强度类型:`, {
                from: hazard.sampling.strengthType,
                to: defaultStrength
              })
              hazard.sampling.strengthType = defaultStrength
            }
          } else {
            console.log(`🔒 使用强制强度类型:`, forcedStrength)
            hazard.sampling.strengthType = forcedStrength
          }

          let effTimeType = hazard.sampling.timeType
          if (!forcedTime) {
            const defaultTime = getDefaultTimeType(hazard)
            if (hazard.sampling.timeType !== defaultTime) {
              console.log(`🔄 设置默认时间类型:`, {
                from: hazard.sampling.timeType,
                to: defaultTime
              })
              hazard.sampling.timeType = defaultTime
            }
            effTimeType = defaultTime
          } else {
            console.log(`🔒 使用强制时间类型:`, forcedTime)
            hazard.sampling.timeType = forcedTime
            effTimeType = forcedTime
          }

          if (String(hazard.type) === '1') {
            hazard.sampling.flowRate = '—'
            console.log(`ℹ️ 类型1危害，设置流量为: —`)
          } else {
            if (effTimeType === 'short') {
              const shortFlow = (hazard as any).shortTimeFlow || (hazard as any).short_time_flow || (hazard as any).short_time_flow1 || hazard.sampling.flowRate
              if (hazard.sampling.flowRate !== shortFlow) {
                console.log(`🔄 设置短时流量:`, { from: hazard.sampling.flowRate, to: shortFlow })
                hazard.sampling.flowRate = shortFlow
              }
            } else if (effTimeType === 'long') {
              const longFlow = (hazard as any).longTimeFlow || (hazard as any).long_time_flow || (hazard as any).long_time_flow1 || hazard.sampling.flowRate
              if (hazard.sampling.flowRate !== longFlow) {
                console.log(`🔄 设置长时流量:`, { from: hazard.sampling.flowRate, to: longFlow })
                hazard.sampling.flowRate = longFlow
              }
            }
          }
        }

        console.log(`✅ 危害初始化完成:`, {
          timeType: hazard.sampling?.timeType,
          strengthType: hazard.sampling?.strengthType,
          flowRate: hazard.sampling?.flowRate
        })
      })
    }
  })

  // 二次矫正
  console.log('🔧 开始二次矫正...')
  try {
    const isFixedWorkMode = (position?.workMode || '') === '固定'
    const ctVal = typeof originalRow.contactTime === 'string' ? parseFloat(originalRow.contactTime || '0') : originalRow.contactTime || 0

    if (isFixedWorkMode && ctVal > 1) {
      (originalRow.hazards || []).forEach((hz: any, index: number) => {
        console.log(`🔍 二次矫正危害 [${index + 1}/${originalRow.hazards.length}]:`, {
          name: hz.cnName
        })

        if (!hz?.sampling) {
          console.log(`ℹ️ 危害无采样信息，跳过`)
          return
        }

        const fTime = (hz as any).__forceTimeType
        if (fTime) {
          console.log(`🔄 应用强制时间类型:`, { from: hz.sampling.timeType, to: fTime })
          hz.sampling.timeType = fTime
          if (fTime === 'short') {
            const shortFlow = hz.shortTimeFlow || hz.short_time_flow || hz.sampling.flowRate
            hz.sampling.flowRate = shortFlow
            console.log(`🔄 设置短时流量:`, shortFlow)
          } else if (fTime === 'long') {
            const longFlow = hz.longTimeFlow || hz.long_time_flow || hz.sampling.flowRate
            hz.sampling.flowRate = longFlow
            console.log(`🔄 设置长时流量:`, longFlow)
          }
        } else {
          console.log(`ℹ️ 无强制时间类型，保持原样`)
        }
      })
      console.log(`✅ 二次矫正完成`)
    }
  } catch(e) {
    console.error('💥 二次矫正异常', e)
  }

  position.tableData = [...position.tableData]
  console.log(`✅ 表格数据更新完成`)

  const currentTabIdx = tabList.value.findIndex((tab) => tab.id === activeTab.value)
  if (currentTabIdx !== -1) {
    tabList.value[currentTabIdx] = { ...tabList.value[currentTabIdx] }
    console.log(`✅ 标签页数据更新完成:`, { tabIndex: currentTabIdx })
  }

  console.log('🏁 === [DEBUG-FIX] 危害更新完成 ===')
  console.log('📊 最终数据状态:')
  surveyStore.printSurveyData()
}

// 同步接触时间到劳动者行：workLocation=2 的危害 contactTime = 所有 workLocation=1 中同名危害的 contactTime 总和
// 同步接触时间到劳动者行：workLocation=2 的危害 contactTime = 所有 workLocation=1 中同名危害的 contactTime 总和
const syncContactTimeToLaborers = (position: any) => {
  console.log('[同步接触时间] 开始同步岗位的接触时间')
  console.log(`[同步接触时间] 岗位名称: ${position.name}`)

  // 获取所有 workLocation=1 的行
  const workplaceRows = position.tableData.filter((row: any) => row.workLocation === 1)
  console.log(`[同步接触时间] 找到 ${workplaceRows.length} 个工作地点行 (workLocation=1)`)

  // 获取所有 workLocation=2 的行（劳动者）
  const laborerRows = position.tableData.filter((row: any) => row.workLocation === 2)
  console.log(`[同步接触时间] 找到 ${laborerRows.length} 个劳动者行 (workLocation=2)`)

  if (laborerRows.length === 0) {
    console.log('[同步接触时间] 没有劳动者行，跳过同步')
    return
  }

  // 统计每个危害的接触时间总和（按 cnName 分组）
  const hazardContactTimeMap = new Map<string, number>()

  workplaceRows.forEach((row: any) => {
    if (!row.hazards || row.hazards.length === 0) {
      return
    }

    // 临时 Map，用于处理当前行内的去重
    // 如果同一行拆分出了 TWA 和 STEL，它们名字相同，时间也相同（或不同），我们只取最大的那个计入总时间
    // 避免 8h(TWA) + 8h(STEL) = 16h 的情况
    const rowHazardMaxTimeMap = new Map<string, number>()

    row.hazards.forEach((hazard: any) => {
      const cnName = hazard.cnName
      // 优先使用 hazard 上的 contactTime，如果没有则使用行的 contactTime
      const contactTime = parseFloat(hazard.contactTime || row.contactTime || '0')

      const currentMax = rowHazardMaxTimeMap.get(cnName) || 0
      if (contactTime > currentMax) {
        rowHazardMaxTimeMap.set(cnName, contactTime)
      }
    })

    // 将当前行去重后的时间累加到全局 Map 中
    rowHazardMaxTimeMap.forEach((time, cnName) => {
      const currentTotal = hazardContactTimeMap.get(cnName) || 0
      hazardContactTimeMap.set(cnName, currentTotal + time)
      console.log(
        `[同步接触时间]   危害 "${cnName}" (工位: ${row.testItem}) 时间累加: ${currentTotal} + ${time} = ${currentTotal + time}`
      )
    })
  })

  console.log('[同步接触时间] 接触时间统计完成:')
  hazardContactTimeMap.forEach((total, cnName) => {
    console.log(`[同步接触时间]   "${cnName}": ${total} 小时`)
  })

  // 更新所有劳动者行中的危害接触时间
  laborerRows.forEach((laborerRow: any) => {
    if (!laborerRow.hazards || laborerRow.hazards.length === 0) {
      console.log(`[同步接触时间] 劳动者行 ${laborerRow.id} 没有危害，跳过`)
      return
    }

    console.log(`[同步接触时间] 更新劳动者行 ${laborerRow.id} 的危害接触时间`)
    laborerRow.hazards.forEach((hazard: any) => {
      const cnName = hazard.cnName
      const totalContactTime = hazardContactTimeMap.get(cnName) || 0
      const oldContactTime = hazard.contactTime

      // 更新危害的接触时间
      hazard.contactTime = totalContactTime.toString()

      // 同时更新采样信息中的接触时间
      if (hazard.sampling) {
        hazard.sampling.contactHours = totalContactTime
      }

      console.log(
        `[同步接触时间]   危害 "${cnName}" 接触时间更新: ${oldContactTime} -> ${totalContactTime}`
      )
    })
  })

  console.log('[同步接触时间] 同步完成')
}

// 添加处理采样类型变更的方法
const handleSamplingChange = (row: ExpandedTableItem) => {
  if (!row.hazard || !row.hazard.sampling) return

  // 找到所在的岗位
  const position = findPositionByRow(row)
  if (!position) {
    console.error('找不到所在岗位')
    return
  }

  // 找到原始行
  const originalRowId = row.originalId
  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) {
    console.error('找不到原始行')
    return
  }

  // 从原始行中找到匹配的危害
  const hazardId = row.hazard.id
  const hazardIndex = originalRow.hazards.findIndex((h) => h.id === hazardId)
  if (hazardIndex === -1) {
    console.error('找不到对应危害')
    return
  }
  // 确保危害有sampling属性
  if (!originalRow.hazards[hazardIndex].sampling) {
    // 将contactTime转为数字
    const contactTime =
      typeof originalRow.contactTime === 'string'
        ? parseFloat(originalRow.contactTime || '0')
        : originalRow.contactTime || 0

    originalRow.hazards[hazardIndex].sampling = {
      sampleDays: 1,
      pointCount: 1,
      sampleCount: 1,
      contactHours: contactTime,
      startDay: 1,
      timeType: 'long',
      sampleType: 'none',
      isCustomTime: false,
      sampleDuration: 0,
      flowRate: 0,
      strengthType: 1
    }
  }

  // 更新采样类型
  if (originalRow.hazards[hazardIndex].sampling && row.hazard.sampling) {
    originalRow.hazards[hazardIndex].sampling.sampleType = row.hazard.sampling.sampleType
    console.log(`危害ID=${hazardId}的采样类型已更新为: ${row.hazard.sampling.sampleType}`)
  }

  // 强制更新表格数据
  position.tableData = [...position.tableData]

  // 强制刷新表格，确保计算属性重新计算
  forceRefresh()

  // 立即保存数据
  console.log('采样类型更新后立即保存数据...')
  surveyStore.printSurveyData()
  console.log(`=== 采样类型更新完成 ===`)
}

// 添加处理长短时间类型变更的方法
const handleTimeTypeChange = (row: ExpandedTableItem) => {
  if (!row.hazard || !row.hazard.sampling) return
  console.log(`=== 长短时间类型更新开始 ===`)
  console.log(`长短时间类型更新为: ${row.hazard.sampling.timeType}`)

  // 找到所在的岗位
  const position = findPositionByRow(row)
  if (!position) {
    console.error('找不到所在岗位')
    return
  }

  // 找到原始行
  const originalRowId = row.originalId
  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) {
    console.error('找不到原始行')
    return
  }

  // 从原始行中找到匹配的危害
  const hazardId = row.hazard.id
  const hazardIndex = originalRow.hazards.findIndex((h) => h.id === hazardId)
  if (hazardIndex === -1) {
    console.error('找不到对应危害')
    return
  }

  // 确保危害有sampling属性
  if (!originalRow.hazards[hazardIndex].sampling) {
    // 将contactTime转为数字
    const contactTime =
      typeof originalRow.contactTime === 'string'
        ? parseFloat(originalRow.contactTime || '0')
        : originalRow.contactTime || 0

    // 初始化采样属性，并应用业务规则
    const hazard = originalRow.hazards[hazardIndex]
    const sampleType = originalRow.workLocation === 1 ? 'fix' : 'personal'

    originalRow.hazards[hazardIndex].sampling = {
      sampleDays: 1,
      pointCount: 1,
      sampleCount: 1,
      contactHours: contactTime,
      startDay: 1,
      timeType: 'long',
      sampleType: sampleType,
      isCustomTime: false,
      sampleDuration: 0,
      flowRate: 0,
      strengthType: 0
    }
  }

  // 更新长短时间类型
  if (originalRow.hazards[hazardIndex].sampling) {
    originalRow.hazards[hazardIndex].sampling.timeType = row.hazard.sampling.timeType
    console.log(`危害ID=${hazardId}的长短时间类型已更新为: ${row.hazard.sampling.timeType}`)
  }

  // 强制更新表格数据
  position.tableData = [...position.tableData]

  // 立即保存数据
  console.log('长短时间类型更新后立即保存数据...')
  surveyStore.printSurveyData()
  console.log(`=== 长短时间类型更新完成 ===`)
}

// 修改 fetchHazardInfo 方法：增加按名称查询的兜底逻辑
const fetchHazardInfo = async (hazard: Hazard) => {
  try {
    // 1. 判断 ID 是否可能是临时 ID (时间戳通常 > 10位)
    const isTempId = String(hazard.id).length > 10
    let response = null

    console.log(`[DEBUG-FIX] 开始获取危害详情: ${hazard.cnName} (ID: ${hazard.id}, IsTemp: ${isTempId})`)

    // 2. 如果不是临时 ID，先尝试用 ID 查
    if (!isTempId) {
      try {
        response = await HazardsApi.getHazards(hazard.id)
      } catch (e) {
        console.warn(`[DEBUG-FIX] ID查询失败，将尝试按名称查询`)
      }
    }

    // 3. 辅助函数：检查 API 返回的数据是否包含核心元数据(流量)
    const hasFlowData = (res: any) => {
      return res && (
        (res.longTimeFlow !== undefined && res.longTimeFlow !== '' && res.longTimeFlow !== '—') ||
        (res.long_time_flow !== undefined && res.long_time_flow !== '' && res.long_time_flow !== '—')
      )
    }

    // 4. 如果 ID 没查到，或者查到的数据里没有流量信息（说明可能是无效ID返回了空对象），则用名称兜底查
    if (!response || (!hasFlowData(response) && String(hazard.type) === '2')) {
      console.log(`[DEBUG-FIX] ID查询数据不全或为临时ID，尝试按名称查询: ${hazard.cnName}`)
      try {
        const nameRes = await HazardsApi.getByName(hazard.cnName)
        // getByName 可能返回 { data: ... } 或直接返回对象，视 API 定义而定
        response = nameRes.data || nameRes

        if (response) {
          // 如果按名称查到了，把真实的字典 ID 也更新回去，避免下次还用临时 ID
          console.log(`[DEBUG-FIX] 按名称查询成功，更新 ID: ${hazard.id} -> ${response.id}`)
          // 注意：这里是否更新 ID 取决于业务是否允许替换。通常替换为字典 ID 是安全的。
          // hazard.id = response.id
        }
      } catch (e) {
        console.error(`[DEBUG-FIX] 按名称查询也失败: ${hazard.cnName}`, e)
      }
    }

    // 5. 数据回填
    if (response) {
      hazard.mac = response.mac
      hazard.pcTwa = response.pcTwa
      hazard.pcStel = response.pcStel
      hazard.type = response.type
      hazard.onlyReco = response.onlyReco === true

      // 【关键】确保流量信息被正确赋值
      const longFlow = response.longTimeFlow || response.long_time_flow
      const shortFlow = response.shortTimeFlow || response.short_time_flow

        // 赋值给 hazard (使用 any 绕过类型检查，确保属性存在)
      ;(hazard as any).longTimeFlow = longFlow
      ;(hazard as any).long_time_flow = longFlow
      ;(hazard as any).shortTimeFlow = shortFlow
      ;(hazard as any).short_time_flow = shortFlow

      console.log(`[DEBUG-FIX] 危害 ${hazard.cnName} 元数据已更新: LongFlow=${longFlow}, ShortFlow=${shortFlow}`)
    }

    // ... (保持原有的列表处理逻辑: 检测依据、测量设备等) ...
    // 检测依据
    if (response && response.testStandard) {
      const arr = response.testStandard.split(/[、,]/).map((s: string) => s.trim()).filter(Boolean)
      hazard.testStandardList = arr
      if (!hazard.testStandard) hazard.testStandard = arr[0] || ''
    }
    // 测量设备
    if (response && response.measuringEquipment) {
      const arr = response.measuringEquipment.split(/[、,]/).map((s: string) => s.trim()).filter(Boolean)
      hazard.measuringEquipmentList = arr
      if (!hazard.measuringEquipment) hazard.measuringEquipment = arr[0] || ''
    }
    // 保存期限
    if (response && response.storageLife) {
      const arr = response.storageLife.split(/[、,]/).map((s: string) => s.trim()).filter(Boolean)
      hazard.storageLifeList = arr
      if (!hazard.storageLife) hazard.storageLife = arr[0] || ''
    }
    // 空气收集器
    if (response && response.airCollectors) {
      const arr = response.airCollectors.split(/[、,]/).map((s: string) => s.trim()).filter(Boolean)
      hazard.airCollectorList = arr
      if (!hazard.airCollector) {
        hazard.airCollector = arr[0] || ''
        hazard.airCollectorIds = arr.length > 0 ? [1] : []
      }
    }

  } catch (error) {
    console.error(`[DEBUG-FIX] 获取危害信息完全失败: ${hazard.cnName}`, error)
  }
}


// 修改处理空气收集器变更的函数
const handleAirCollectorChange = (row: ExpandedTableItem, value: string | string[]) => {
  console.log('=== 空气收集器变更 ===')
  console.log('当前行:', row)
  console.log('新值:', value)

  // 确保 value 是数组
  const valueArray = Array.isArray(value) ? value : [value]

  // 找到所在的岗位
  const position = findPositionByRow(row)
  if (!position) {
    console.error('找不到所在岗位')
    return
  }

  // 找到原始行
  const originalRowId = row.originalId
  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) {
    console.error('找不到原始行')
    return
  }

  if (row.hazard) {
    // 如果是危害行，更新危害的空气收集器
    const hazardId = row.hazard.id
    const hazardIndex = originalRow.hazards.findIndex((h) => h.id === hazardId)
    if (hazardIndex !== -1) {
      // 更新危害的空气收集器数据
      originalRow.hazards[hazardIndex].airCollector = valueArray.join('、')
      originalRow.hazards[hazardIndex].airCollectorList = [...valueArray]
      originalRow.hazards[hazardIndex].airCollectorIds = valueArray.map((_, index) => index + 1)
    }
  }

  // 强制更新表格数据
  position.tableData = [...position.tableData]

  // 立即保存数据
  setTimeout(() => {
    surveyStore.printSurveyData()
  }, 200)
}

// 添加更新当前岗位ID的函数
const handleContactTimeChange = async (row: ExpandedTableItem) => {
  console.log('=== 处理接触时间变更开始 ===')
  console.log('当前行数据:', JSON.stringify(row))

  // 验证并格式化值
  let value = row.contactTime
  if (isNaN(Number(value)) || Number(value) < 0) {
    value = '0'
  }
  if (Number(value) > 24) {
    value = '24'
  }

  // 更新当前行的接触时间
  row.contactTime = value
  console.log('更新后的接触时间:', value)

  // 获取当前岗位
  const currentTab = tabList.value.find((tab) => tab.id === activeTab.value)
  if (!currentTab) {
    console.error('未找到当前车间')
    return
  }

  // 在原始数据中找到对应的行
  const originalRowId = (row as any).originalId || row.id
  const originalRow = currentTab.positions
    .flatMap((pos) => pos.tableData)
    .find((item) => item.id === originalRowId)
  if (originalRow) {
    // 校验：跨车间（同名岗位）所有工位接触时间总和不得超过岗位工作时间
    const position = findPositionByRow(row)
    const valueNum = Number(value)
    if (position) {
      const validation = validateContactTimeTotalForPositionGlobal(position, originalRow, valueNum)
      if (!validation.isValid) {
        ElMessage.warning(validation.message)
        // 恢复界面显示
        row.contactTime = String(originalRow.contactTime ?? '0')
        return
      }
    }
    console.log('找到原始行数据:', originalRow)
    originalRow.contactTime = value

    // 如果是项目行，更新所有相关危害的接触时间
    if (originalRow.hazards) {
      originalRow.hazards.forEach((hazard) => {
        if (hazard.contactTime !== undefined) {
          hazard.contactTime = value
          console.log('更新危害的接触时间:', hazard.id, value)
        }
      })
    }

    if (originalRow.workLocation === 1 && originalRow.hazards && originalRow.hazards.length > 0) {
      console.log('[接触时间变更] 触发危害拆分规则重算')
      await recalculateRowHazards(originalRow)
    }

    // 如果是 workLocation=1 的行，需要同步接触时间到 workLocation=2 的行
    if (originalRow.workLocation === 1) {
      const position = findPositionByRow(row)
      if (position) {
        console.log('[接触时间变更] 触发同步接触时间到劳动者行')
        syncContactTimeToLaborers(position)
      }
    }
  } else {
    console.error('未找到原始行数据')
  }

  // 立即保存到store
  console.log('保存数据到store')
  surveyStore.printSurveyData()

  console.log('=== 处理接触时间变更完成 ===')
}

const handleHazardSamplingChange = (row, field) => {
  if (!row.hazard?.sampling) return
  const value = Number(row.hazard.sampling[field])
  if (isNaN(value)) {
    row.hazard.sampling[field] = field === 'sampleDuration' ? 0 : 1
    return
  }
  row.hazard.sampling[field] = value
  if (field !== 'sampleDuration' && value < 1) {
    row.hazard.sampling[field] = 1
  }
  if (field === 'sampleDuration' && value < 0) {
    row.hazard.sampling[field] = 0
  }

  // 当修改每天点数时，按 testItem 同步到同组的所有危害（任意一行修改都联动）
  if (field === 'pointCount') {
    const position = findPositionByRow(row)
    if (position) {
      const currentTestItem = row.testItem
      position.tableData.forEach((tableRow) => {
        if (tableRow.testItem === currentTestItem && Array.isArray(tableRow.hazards)) {
          tableRow.hazards.forEach((hz) => {
            if (!hz.sampling) {
              // 若不存在 sampling，则初始化后再赋值
              const contactTime =
                typeof tableRow.contactTime === 'string'
                  ? parseFloat(tableRow.contactTime || '0')
                  : tableRow.contactTime || 0
              hz.sampling = {
                sampleDays: 1,
                pointCount: 1,
                sampleCount: 1,
                contactHours: contactTime,
                startDay: 1,
                timeType: 'long',
                sampleType: tableRow.workLocation === 1 ? 'fix' : 'personal',
                isCustomTime: false,
                sampleDuration: 0,
                flowRate: 0,
                strengthType: 1
              }
            }
            hz.sampling.pointCount = Number.isFinite(value) && value >= 1 ? value : 1
          })
        }
      })
      // 触发视图更新
      position.tableData = [...position.tableData]
    }
  }
}

// 获取当前行所属岗位的作业类型
const getPositionWorkMode = (row: any) => {
  const position = findPositionByRow(row)
  return position?.workMode || ''
}

// [修改] 复制方法
const handleCopy = (row: TableItem) => {
  const originalRowId = row.id.split('_hazard_')[0]

  // 1. 全局查找岗位 (使用修改后的 findPositionByRow)
  const position = findPositionByRow(row)
  if (!position) return

  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) return

  if (originalRow.workLocation === 2) {
    ElMessage.warning('劳动者行不支持复制')
    return
  }

  // 2. 接触时间校验 (跨车间总和)
  try {
    const positionName = position.name
    const addTime = Number(originalRow.contactTime)
    const delta = Number.isFinite(addTime) ? addTime : 0
    const currentTotal = getCrossWorkshopContactTimeTotal(positionName)
    const workHours = getCrossWorkshopWorkHours(positionName)
    const proposed = currentTotal + delta
    if (proposed > workHours) {
      ElMessage.warning(`【${positionName}】所有工位接触时间总和(${proposed.toFixed(1)}h)将超过岗位工作时间(${workHours}h)，已取消复制`)
      return
    }
  } catch {}

  // 3. 执行复制
  const newRow: TableItem = JSON.parse(JSON.stringify(originalRow))
  const timestamp = Date.now()
  newRow.id = `${originalRowId}_copy_${timestamp}`
  newRow.rowKey = `${originalRowId}_copy_${timestamp}`
  newRow.originalId = newRow.id

  // 自动重命名 testItem
  if (newRow.testItem) {
    const baseTestItem = newRow.testItem.replace(/\d+$/, '')
    const existingTestItems = position.tableData.map((item) => item.testItem)
    let maxNum = 0
    existingTestItems.forEach((item) => {
      if (item && item.startsWith(baseTestItem)) {
        const match = item.match(/\d+$/)
        if (match) {
          const num = parseInt(match[0])
          maxNum = Math.max(maxNum, num)
        }
      }
    })
    newRow.testItem = `${baseTestItem}${maxNum + 1}`
  }

  // 插入新行
  const nonLaborRows = position.tableData.filter((r) => r.workLocation !== 2)
  const laborRows = position.tableData.filter((r) => r.workLocation === 2)

  // 找到插入位置
  const originIdxInNonLabor = nonLaborRows.findIndex((r) => r.id === originalRowId)
  const insertIdx = originIdxInNonLabor >= 0 ? originIdxInNonLabor + 1 : nonLaborRows.length
  nonLaborRows.splice(insertIdx, 0, newRow)

  position.tableData = [...nonLaborRows, ...laborRows]

  // 4. 关键：触发同步和保存
  syncContactTimeToLaborers(position)
  ElMessage.success('复制成功')
  surveyStore.printSurveyData()
}

// 查找岗位所属的车间
// 新增：根据岗位查找所属车间
const findWorkshopByPosition = (position: any) => {
  for (const tab of tabList.value) {
    if (tab.positions && tab.positions.includes(position)) {
      return tab;
    }
  }
  return null;
}


// 新增：跨车间（同名岗位）的总接触时间计算与校验
const getCrossWorkshopContactTimeTotal = (positionName: string): number => {
  let total = 0
  try {
    tabList.value.forEach((wk) => {
      ;(wk.positions || [])
        .filter((p: any) => !p?.isDeleted && p?.name === positionName)
        .forEach((p: any) => {
          ;(p.tableData || [])
            .filter((r: any) => Number(r.workLocation) === 1)
            .forEach((r: any) => {
              const t = Number(r.contactTime)
              total += Number.isFinite(t) ? t : 0
            })
        })
    })
  } catch {}
  return Number.isFinite(total) ? total : 0
}

const getCrossWorkshopWorkHours = (positionName: string): number => {
  for (const wk of tabList.value) {
    for (const p of wk.positions || []) {
      if (!p?.isDeleted && p?.name === positionName) {
        const h = Number(p.workHours)
        return Number.isFinite(h) && h > 0 ? h : 8
      }
    }
  }
  return 8
}

const validateContactTimeTotalForPositionGlobal = (
  position: any,
  currentRow: any,
  newContactTime: number
): { isValid: boolean; message: string } => {
  const positionName = position?.name || ''
  const workHours = getCrossWorkshopWorkHours(positionName)
  let total = 0
  try {
    tabList.value.forEach((wk) => {
      ;(wk.positions || [])
        .filter((p: any) => !p?.isDeleted && p?.name === positionName)
        .forEach((p: any) => {
          ;(p.tableData || [])
            .filter((r: any) => Number(r.workLocation) === 1)
            .forEach((r: any) => {
              if (p.id === position.id && r.id === currentRow.id) {
                total += Number.isFinite(newContactTime) ? newContactTime : 0
              } else {
                const t = Number(r.contactTime)
                total += Number.isFinite(t) ? t : 0
              }
            })
        })
    })
  } catch {}
  const ok = total <= workHours
  const message = ok
    ? ''
    : `【${positionName}】所有工位接触时间总和(${total.toFixed(1)}h)超过岗位工作时间(${workHours}h)，请调整`
  return { isValid: ok, message }
}

// 修改：处理接触频度变更 (移除 activeTab 依赖，支持跨车间计算)
const handleContactFrequencyChange = async (
  row: ExpandedTableItem,
  field: 'count' | 'duration' | 'interval'
) => {
  console.log('=== 处理接触频度变更开始 ===')

  // 1. 找到行所属的岗位 (这是真理来源，可能在非当前Tab中)
  const position = findPositionByRow(row)
  if (!position) {
    console.error('找不到所在岗位')
    return
  }

  // 2. 找到原始行
  const originalRowId = row.originalId
  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) {
    console.error('找不到原始行')
    return
  }

  // 3. 数值处理
  let value = Number(row.contactFrequency?.[field])
  if (isNaN(value)) value = 0
  if (value < 0) value = 0

  // 备份旧值（用于验证失败回滚）
  let originalValue = 0
  if (row.hazard) {
    const hazardId = row.hazard.id
    const hazardIndex = originalRow.hazards.findIndex((h) => h.id === hazardId)
    if (hazardIndex !== -1 && originalRow.hazards[hazardIndex].contactFrequency) {
      originalValue = originalRow.hazards[hazardIndex].contactFrequency[field] || 0
    }
  } else if (originalRow.contactFrequency) {
    originalValue = originalRow.contactFrequency[field] || 0
  }

  // 4. 更新数据对象
  // 优先更新视图行
  if (!row.contactFrequency) row.contactFrequency = { count: 1, duration: 1, interval: 1 }
  row.contactFrequency[field] = value

  // 同步更新原始数据 (originalRow)
  let updated = false
  if (row.hazard) {
    const hazardId = row.hazard.id
    const hazardIndex = originalRow.hazards.findIndex((h) => h.id === hazardId)
    if (hazardIndex !== -1) {
      if (!originalRow.hazards[hazardIndex].contactFrequency) {
        originalRow.hazards[hazardIndex].contactFrequency = { count: 1, duration: 1, interval: 1 }
      }
      originalRow.hazards[hazardIndex].contactFrequency[field] = value
      updated = true
    }
  }
  if (!updated || row.isFirstHazard) {
    if (!originalRow.contactFrequency) originalRow.contactFrequency = { count: 1, duration: 1, interval: 1 }
    originalRow.contactFrequency[field] = value
  }

  // 5. 强制触发视图更新 (让输入框立刻响应)
  position.tableData = [...position.tableData]

  // 6. 【核心修复】直接使用 position 对象判断，不依赖 activeTab
  // 只要接触类型不是"稳定"，就需要计算接触时间 (流动岗位通常也是非稳定)
  if (position.workPosition !== '稳定') {
    console.log(`[接触频度变更] 岗位 "${position.name}" (类型: ${position.workPosition}) 触发计算`)

    const countSrc = row.contactFrequency?.count ?? 0
    const durationSrc = row.contactFrequency?.duration ?? 0

    let computed = Number(countSrc) * Number(durationSrc)
    if (isNaN(computed) || computed < 0) computed = 0
    if (computed > 24) computed = 24
    console.log(`[接触频度变更] 计算结果: ${countSrc} × ${durationSrc} = ${computed}小时`)

    // 校验总时间 (跨车间校验)
    const validation = validateContactTimeTotalForPositionGlobal(position, originalRow, computed)

    if (!validation.isValid) {
      console.log(`[接触频度变更] 验证失败，恢复原值`)
      ElMessage.warning(validation.message)

      // 回滚逻辑
      row.contactFrequency[field] = originalValue
      if (row.hazard) {
        const idx = originalRow.hazards.findIndex((h) => h.id === row.hazard.id)
        if(idx !== -1) originalRow.hazards[idx].contactFrequency[field] = originalValue
      } else {
        originalRow.contactFrequency[field] = originalValue
      }

      position.tableData = [...position.tableData]
      return
    }

    // 7. 应用新时间
    const newTimeStr = String(computed)
    row.contactTime = newTimeStr
    originalRow.contactTime = newTimeStr

    // 同步到该工位(testItem)的所有行 (针对多危害情况)
    const currentTestItem = row.testItem
    position.tableData.forEach((tableRow) => {
      if (tableRow.testItem === currentTestItem) {
        tableRow.contactTime = newTimeStr
        // 同步到危害内部
        if (tableRow.hazards && tableRow.hazards.length > 0) {
          tableRow.hazards.forEach((hazard) => {
            hazard.contactTime = newTimeStr
          })
        }
      }
    })

    // 8. 触发危害重算 (时间变了，拆分规则可能变)
    if (originalRow.hazards && originalRow.hazards.length > 0) {
      console.log('[接触频度变更] 接触时间已更新，触发危害重算')
      await recalculateRowHazards(originalRow)
    }

    // 9. 再次更新视图并同步劳动者
    position.tableData = [...position.tableData]
    syncContactTimeToLaborers(position)
  } else {
    console.log(`[接触频度变更] 岗位类型为 ${position.workPosition}，不触发自动计算`)
  }

  // 保存
  surveyStore.printSurveyData()
}

// 更新工作内容、来源和接触时间数据
const updateCommonFieldData = (row: TableItem, field: string, value?: string) => {
  console.log('updateCommonFieldData - 开始更新字段:', field)
  console.log('updateCommonFieldData - 当前行:', row)

  // 找到所在的岗位
  const position = findPositionByRow(row)
  if (!position) {
    console.log('updateCommonFieldData - 未找到当前岗位')
    return
  }

  // 找到原始行
  const originalRowId = row.originalId
  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) {
    console.log('updateCommonFieldData - 未找到原始行')
    return
  }

  if (!row.hazards?.[0]) {
    console.log('updateCommonFieldData - 当前行没有 hazards 数据')
    return
  }

  const currentTestItem = row.testItem
  const currentValue = value !== undefined ? value : (row.hazards?.[0]?.[field] ?? row[field])

  console.log('updateCommonFieldData - 当前测试项:', currentTestItem)
  console.log('updateCommonFieldData - 当前值:', currentValue)

  // 更新相同 testItem 的所有行的所有危害
  position.tableData.forEach((tableRow) => {
    if (tableRow.testItem === currentTestItem && tableRow.hazards?.length > 0) {
      console.log('updateCommonFieldData - 更新行:', tableRow.id)
      tableRow.hazards.forEach((hazard) => {
        console.log('updateCommonFieldData - 更新危害:', hazard.id)
        hazard[field] = currentValue
      })
      // 也同步 tableRow 的 workContent 字段
      tableRow[field] = currentValue
    }
  })

  // 触发视图更新
  position.tableData = [...position.tableData]

  // 保存数据
  setTimeout(() => {
    surveyStore.printSurveyData()
  }, 200)
}

const handleContactTimingChange = (row: TableItem, value: string) => {
  console.log('handleContactTimingChange - 修改前:', row.hazards?.[0]?.contactTiming)
  console.log('handleContactTimingChange - 新值:', value)

  // 找到所在的岗位
  const position = findPositionByRow(row)
  if (!position) {
    console.log('handleContactTimingChange - 未找到当前岗位')
    return
  }

  const currentTestItem = row.testItem

  // 更新所有相同 testItem 的行的所有危害
  position.tableData.forEach((tableRow) => {
    if (tableRow.testItem === currentTestItem && tableRow.hazards?.length > 0) {
      console.log('handleContactTimingChange - 更新行:', tableRow.id)
      tableRow.hazards.forEach((hazard) => {
        console.log('handleContactTimingChange - 更新危害:', hazard.id)
        console.log('handleContactTimingChange - 原值:', hazard.contactTiming)
        // 如果值为空，则使用 workContent + "时"，如果都没有则使用默认值
        const newValue = value || (hazard.workContent ? `${hazard.workContent}时` : '')
        hazard.contactTiming = newValue
        console.log('handleContactTimingChange - 新值:', hazard.contactTiming)
      })
    }
  })

  // 触发视图更新
  position.tableData = [...position.tableData]

  // 保存数据
  setTimeout(() => {
    surveyStore.printSurveyData()
  }, 200)
}

// 在 setup 里添加：
const testItemInputRef = ref()

const handleEditTestItem = (row) => {
  row.editingTestItem = true
  row.editingTestItemValue = row.testItem
  nextTick(() => {
    if (testItemInputRef.value && testItemInputRef.value.input) {
      testItemInputRef.value.input.focus()
    }
  })
}

const handleSaveTestItem = (row) => {
  console.log(`[保存工作地点] 开始处理工作地点修改`)
  const value = (row.editingTestItemValue || '').trim()
  console.log(`[保存工作地点] 新工作地点: "${value}"`)
  console.log(`[保存工作地点] 原工作地点: "${row.testItem}"`)

  if (!value) {
    console.log(`[保存工作地点] 工作地点为空，操作终止`)
    ElMessage.warning('检测项目不能为空')
    row.editingTestItemValue = row.testItem
    row.editingTestItem = false
    return
  }

  const oldValue = row.testItem

  // 找到岗位
  const position = findPositionByRow(row)
  console.log(
    `[保存工作地点] 找到岗位:`,
    position
      ? {
        name: position.name,
        id: position.id,
        tableDataLength: position.tableData?.length || 0
      }
      : '未找到'
  )

  if (position) {
    // 检查同一岗位下工作地点名称的唯一性
    const duplicateRow = position.tableData.find(
      (item) => item.id !== row.id && item.testItem === value
    )

    if (duplicateRow) {
      console.log(`[保存工作地点] 工作地点"${value}"已存在，操作终止`)
      ElMessage.warning(`工作地点"${value}"已存在，请使用不同的名称`)
      row.editingTestItemValue = row.testItem
      row.editingTestItem = false
      return
    }

    // 找到 tableData 里对应的行
    const targetRow = position.tableData.find((item) => item.id === row.id)
    console.log(
      `[保存工作地点] 找到目标行:`,
      targetRow
        ? {
          id: targetRow.id,
          testItem: targetRow.testItem,
          hazardsCount: targetRow.hazards?.length || 0
        }
        : '未找到'
    )

    if (targetRow) {
      targetRow.testItem = value
      console.log(`[保存工作地点] 工作地点已更新: "${oldValue}" -> "${value}"`)

      // 工作地点变化时的联动逻辑：更新接触时机、工作内容、来源（不影响岗位名称）
      console.log(`[保存工作地点] 开始调用工作地点联动逻辑`)
      handleWorkplaceChangeWithLinkage(targetRow, oldValue, value)
      console.log(`[保存工作地点] 工作地点联动逻辑调用完成`)
    }
    // 强制刷新
    position.tableData = [...position.tableData]
  }
  row.editingTestItem = false
  console.log(`[保存工作地点] 工作地点修改流程完成`)
  surveyStore.printSurveyData()
}

// 处理工作内容变化
const handleWorkContentChange = (row, value) => {
  console.log('工作内容变化 - 行:', row)
  console.log('工作内容变化 - 新值:', value)
  // 先更新当前行和 hazard 的值
  row.workContent = value
  if (row.hazard) row.hazard.workContent = value
  updateCommonFieldData(row, 'workContent', value)
}

// 处理劳动强度变化
const handleLaborIntensityChange = (row, value) => {
  console.log('劳动强度变化 - 行:', row)
  console.log('劳动强度变化 - 新值:', value)
  // 先更新当前行和 hazard 的值
  row.laborIntensity = value
  if (row.hazard) row.hazard.laborIntensity = value
  updateCommonFieldData(row, 'laborIntensity', value)
}

// 处理来源变化
const handleSourceChange = (row: ExpandedTableItem, value: string) => {
  console.log('=== 处理来源变化开始 ===')
  console.log('当前行:', row)
  console.log('新值:', value)

  // 找到所在的岗位
  const position = findPositionByRow(row)
  if (!position) {
    console.error('找不到所在岗位')
    return
  }

  // 找到原始行
  const originalRowId = row.originalId
  const originalRow = position.tableData.find((item) => item.id === originalRowId)
  if (!originalRow) {
    console.error('找不到原始行')
    return
  }

  // 更新原始行的source
  originalRow.source = value

  // 如果是危害行，只更新当前危害的source
  if (row.hazard) {
    const hazardId = row.hazard.id
    const hazardIndex = originalRow.hazards.findIndex((h) => h.id === hazardId)
    if (hazardIndex !== -1) {
      originalRow.hazards[hazardIndex].source = value
    }
  }

  // 强制更新表格数据
  position.tableData = [...position.tableData]

  // 立即保存数据
  setTimeout(() => {
    surveyStore.printSurveyData()
  }, 200)

  console.log('=== 处理来源变化完成 ===')
}

// 处理危害复制
const handleCopyHazard = (row: ExpandedTableItem, hazard: any) => {
  // 优先用 originalId 查找
  const mainRowId = row.originalId || row.id
  const position = findPositionByRow({ id: mainRowId })
  if (!position) {
    ElMessage.error('未找到岗位')
    return
  }
  const originalRow = position.tableData.find((item) => item.id === mainRowId)
  if (!originalRow || !originalRow.hazards) {
    ElMessage.error('未找到原始行或危害')
    return
  }
  // 深拷贝 hazard 并生成新 id
  const newHazard = JSON.parse(JSON.stringify(hazard))
    // 复制时重置逻辑删除标记
  ;(newHazard as any).deletedInPage1 = false
  ;(newHazard as any).deletedInPage2 = false
  // 生成唯一 id（时间戳+随机数）
  // newHazard.id = `${hazard.id}_copy_${Date.now()}_${Math.floor(Math.random()*10000)}`
  // 保证 worker/contactTiming 字段存在
  if (!('worker' in newHazard)) newHazard.worker = []
  if (!('contactTiming' in newHazard)) newHazard.contactTiming = ''

  // 找到当前 hazard 在 hazards 数组中的索引
  const idx = originalRow.hazards.findIndex((h: any) => h.id === hazard.id)
  if (idx === -1) {
    ElMessage.error('未找到要复制的危害')
    return
  }
  // 在当前 hazard 后面插入新 hazard
  originalRow.hazards.splice(idx + 1, 0, newHazard)

  // 日志输出
  console.log('handleCopyHazard 插入后 hazards:', JSON.stringify(originalRow.hazards))
  position.tableData = [...position.tableData]
  ElMessage.success('危害复制成功')
}

// 新增删除hazard行的方法
const handleDeleteHazardRow = async (row: ExpandedTableItem, hazard: any) => {
  await ElMessageBox.confirm('确定要删除该危害吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })

  const mainRowId = row.originalId || row.id
  const position = findPositionByRow({ id: mainRowId })
  if (!position) {
    ElMessage.error('未找到岗位')
    return
  }
  const originalRow = position.tableData.find((item) => item.id === mainRowId)
  if (!originalRow || !originalRow.hazards) {
    ElMessage.error('未找到原始行或危害')
    return
  }
  const index = originalRow.hazards.findIndex((h) => h.id === hazard.id)
  if (index === -1) {
    ElMessage.error('未找到要删除的危害')
    return
  }
  // 在方案页进行逻辑删除：仅标记 deletedInPage2
  originalRow.hazards[index].deletedInPage2 = true
  originalRow.hazards = [...originalRow.hazards]
  position.tableData = [...position.tableData]
  surveyStore.printSurveyData()
  // 持久化保存
  surveyStore.printSurveyData()

  // 只删除当前行，不同步其他行
  ElMessage.success('危害已删除')
  return
}



// 作业类型与接触类型联动
const handleWorkModeChange = async (val: string, position: any) => {
  console.log(`[DEBUG-FIX] 作业类型切换: ${val}, 岗位: ${position.name}`)

  // 1. 预检查：切换为固定时的约束
  if (val === '固定') {
    try {
      const workLocationCount = Array.isArray(position.tableData)
        ? position.tableData.filter((row: any) => row.workLocation === 1).length
        : 0

      if (workLocationCount > 1) {
        ElMessage.warning(`固定岗位只能有一个工位，当前有 ${workLocationCount} 个，无法切换`)
        nextTick(() => { position.workMode = '流动' })
        return
      }

      const currentWorkshop = typeof findWorkshopByPosition === 'function' ? findWorkshopByPosition(position) : null
      const otherWorkshops = (tabList.value || [])
        .filter((tab: any) => tab.positions?.some((p: any) => !p?.isDeleted && p?.name === position.name))
        .filter((tab: any) => !currentWorkshop || tab.id !== currentWorkshop.id)
        .map((tab: any) => tab.name)

      if (otherWorkshops.length > 0) {
        ElMessage.warning(`岗位【${position.name}】在其他车间也有，无法切换为固定`)
        nextTick(() => { position.workMode = '流动' })
        return
      }
    } catch (e) { console.log(e) }
  }

  // 2. 更新 workMode
  position.workMode = val

  // 3. 确定新的接触类型并更新时间
  let newWorkPosition = ''
  if (val === '固定') newWorkPosition = '稳定'
  else if (val === '流动') newWorkPosition = '非稳定'

  if (newWorkPosition) {
    console.log(`[DEBUG-FIX] 应用接触类型变更: ${newWorkPosition}，将更新接触时间`)
    // 这会将接触时间设为 8h (稳定) 或 频度计算值
    // 注意：applyWorkPositionChangeToPosition 只负责改数值，不负责 heavy logic
    applyWorkPositionChangeToPosition(position, newWorkPosition, '[作业类型切换]')
  }

  // 4. 【关键】接触时间更新后，触发危害重算
  // handleHazardUpdate 会读取 position.workMode 和 row.contactTime 来决定如何拆分
  if (position.tableData && position.tableData.length > 0) {
    console.log('[DEBUG-FIX] 接触时间已就绪，开始重算危害拆分规则...')
    for (const row of position.tableData) {
      if (row.workLocation === 1 && row.hazards && row.hazards.length > 0) {
        // 必须 await，确保每一行都处理完
        await recalculateRowHazards(row)
      }
    }
  }

  // 5. 最后同步劳动者接触时间
  try {
    syncContactTimeToLaborers(position)
  } catch (e) {}

  // 6. 跨车间同步
  try {
    const name = position.name
    const wp = position.workPosition
    tabList.value.forEach((workshop) => {
      workshop.positions?.forEach((pos) => {
        if (pos !== position && !pos?.isDeleted && pos?.name === name) {
          pos.workMode = val
          if (wp) applyWorkPositionChangeToPosition(pos, wp, `[跨车间同步]`)
        }
      })
    })
  } catch (e) {}
}

// 处理接触类型变化
const handleWorkPositionChange = async (val: string, position: any) => {
  // 防御：统一本次新接触类型变量
  const newWorkPosition = val
  const hoursNum = Number(position.workHours || 0)
  const safeHours = isNaN(hoursNum) ? 0 : Math.min(24, Math.max(0, hoursNum))

  console.log('接触类型变化:', val, '岗位:', position.name)

  // 1. 根据类型更新接触时间
  if (val === '非稳定' && Array.isArray(position.tableData)) {
    // 非稳定：由频度计算
    position.tableData.forEach((row: any) => {
      const count = Number(row?.contactFrequency?.count ?? 0)
      const duration = Number(row?.contactFrequency?.duration ?? 0)
      if (!isNaN(count) && !isNaN(duration)) {
        let computed = count * duration
        if (computed < 0) computed = 0
        if (computed > 24) computed = 24
        row.contactTime = String(computed)
      }
    })
  } else if (val === '稳定' && Array.isArray(position.tableData)) {
    // 稳定：等于工作时间
    position.tableData.forEach((row: any) => {
      row.contactTime = String(safeHours)
    })
  }

  // 触发视图更新
  position.tableData = [...position.tableData]

  // 2. 【关键新增】接触时间变化后，必须触发危害重算
  // 因为时间可能从 >1h 变为 <1h，或者反之，这会改变拆分规则
  if (position.tableData && position.tableData.length > 0) {
    console.log('[接触类型变化] 接触时间已更新，开始重算危害拆分规则...')
    for (const row of position.tableData) {
      // 只处理工位行且有危害的行
      if (row.workLocation === 1 && row.hazards && row.hazards.length > 0) {
        await recalculateRowHazards(row)
      }
    }
  }

  // 3. 同步接触时间到劳动者行
  console.log('[接触类型变化] 触发同步接触时间到劳动者行')
  syncContactTimeToLaborers(position)

  // 4. 同步更新 岗位管理弹窗 内的工作地点数据（workplaceData）
  if (Array.isArray(position.workplaceData)) {
    if (val === '非稳定') {
      position.workplaceData.forEach((wp: any) => { wp.contactTime = 0 })
    } else if (val === '稳定') {
      position.workplaceData.forEach((wp: any) => { wp.contactTime = safeHours })
      if (newWorkPosition === '非稳定?') { // 这里的逻辑保留你原有的，虽然后面会被覆盖
        position.workplaceData.forEach((workplace: any) => { workplace.contactTime = 0 })
      }
    }
  }

  // 再校正：非稳定时按频度计算接触时间
  if (val !== '稳定' && Array.isArray(position.workplaceData)) {
    position.workplaceData.forEach((wp: any) => {
      const count = Number(wp?.contactFrequency?.count ?? 0)
      const duration = Number(wp?.contactFrequency?.duration ?? 0)
      const computed = Math.min(Math.max(count * duration, 0), 24)
      wp.contactTime = computed
    })
  }

  // 5. 跨车间同步
  if (!positionTypeDialogVisible.value) {
    try {
      console.log(`[跨车间同步][接触类型] 开始同步岗位 "${position.name}" 到其他车间`)
      const name = position.name
      tabList.value.forEach((workshop) => {
        workshop.positions?.forEach((pos) => {
          if (pos !== position && !pos?.isDeleted && pos?.name === name) {
            // 注意：跨车间同步时，也需要调用 applyWorkPositionChangeToPosition
            // 但为了简化，这里假设 applyWorkPositionChangeToPosition 内部没有复杂的重算逻辑
            // 如果跨车间也要完美同步，最好封装一个公共的 updatePositionTypeLogic 函数
            pos.workPosition = val
            applyWorkPositionChangeToPosition(pos, val, `[跨车间同步][接触类型]`)
            // 跨车间也应该触发重算，但这可能会有性能问题，视需求而定
          }
        })
      })
    } catch (e) {
      console.log('[跨车间同步][接触类型] 同步失败:', e)
    }
  }
}

// 将接触类型变更应用到指定岗位（并联动接触时间）
const applyWorkPositionChangeToPosition = (pos: any, val: string, logPrefix = '[接触类型变化]') => {
  const old = pos.workPosition
  pos.workPosition = val
  const hoursNum = Number(pos.workHours || 0)
  const safeHours = isNaN(hoursNum) ? 0 : Math.min(24, Math.max(0, hoursNum))
  if (val === '非稳定' && Array.isArray(pos.tableData)) {
    pos.tableData.forEach((row: any) => {
      const count = Number(row?.contactFrequency?.count ?? 0)
      const duration = Number(row?.contactFrequency?.duration ?? 0)
      let computed = count * duration
      if (computed < 0) computed = 0
      if (computed > 24) computed = 24
      row.contactTime = String(computed)
    })
    pos.tableData = [...pos.tableData]
  } else if (val === '稳定' && Array.isArray(pos.tableData)) {
    pos.tableData.forEach((row: any) => {
      row.contactTime = String(safeHours)
    })
    pos.tableData = [...pos.tableData]
  }
  // 同步更新 弹窗中的工作地点数据
  if (Array.isArray(pos.workplaceData)) {
    if (val === '非稳定') {
      pos.workplaceData.forEach((wp: any) => {
        wp.contactTime = 0
      })
    } else if (val === '稳定') {
      pos.workplaceData.forEach((wp: any) => {
        wp.contactTime = safeHours
      })
    }
  }
  // 再校正：非稳定时按频度计算接触时间（保留已有频度）；避免被置 0
  if (val !== '稳定' && Array.isArray(pos.workplaceData)) {
    pos.workplaceData.forEach((wp: any) => {
      const count = Number(wp?.contactFrequency?.count ?? 0)
      const duration = Number(wp?.contactFrequency?.duration ?? 0)
      const computed = Math.min(Math.max(count * duration, 0), 24)
      wp.contactTime = computed
    })
  }
  console.log(`${logPrefix} 岗位 "${pos.name}" 接触类型: ${old} -> ${val}`)
}

const workshopList = ref<{ id?: string; name: string }[]>([])

// 处理班制单个岗位变更（基础信息同步）
const handleShiftSystemChange = (value: string, position: any) => {
  try {
    console.log(
      `[岗位基本信息] 岗位 "${position.name}" 班制变更: ${position.shiftSystem} -> ${value}`
    )
    position.shiftSystem = value
    // --- 新增：触发本岗位总人数计算 ---
    calculateTotalPeople(position)
    const name = position.name
    tabList.value.forEach((workshop) => {
      workshop.positions?.forEach((pos) => {
        if (pos !== position && !pos?.isDeleted && pos?.name === name) {
          const old = pos.shiftSystem
          pos.shiftSystem = value
          calculateTotalPeople(pos)
          console.log(
            `[跨车间同步][班制] 车间 "${workshop.name}" 岗位 "${name}" 班制: ${old} -> ${value}`
          )
        }
      })
    })
  } catch (e) {
    console.log('[跨车间同步][班制] 同步失败:', e)
  }
}

// 处理劳动者名单变更（基础信息同步）
const handleWorkerNameChange = (position: any) => {
  try {
    const name = position.name
    const values = Array.isArray(position.workerName) ? [...position.workerName] : []
    console.log(`[岗位基本信息] 岗位 "${name}" 劳动者变更为:`, values)
    tabList.value.forEach((workshop) => {
      workshop.positions?.forEach((pos) => {
        if (pos !== position && !pos?.isDeleted && pos?.name === name) {
          const old = Array.isArray(pos.workerName) ? [...pos.workerName] : []
          pos.workerName = [...values]
          console.log(
            `[跨车间同步][劳动者] 车间 "${workshop.name}" 岗位 "${name}" 劳动者:`,
            old,
            '->',
            values
          )
        }
      })
    })
  } catch (e) {
    console.log('[跨车间同步][劳动者] 同步失败:', e)
  }
}

// 打开弹窗时初始化已有车间
watch(workshopDialogVisible, (val) => {
  if (val) {
    // 打开时带入已有车间，并添加一个空的新车间行
    if (tabList.value.length > 0) {
      workshopList.value = [
        ...tabList.value.map((tab) => ({
          id: tab.id || generateId(),
          name: tab.name
        })),
        { id: generateId(), name: '' } // 添加一个空的新车间行
      ]
    } else {
      workshopList.value = [{ id: generateId(), name: '' }]
    }
  }
})

const addWorkshopRow = (idx: number) => {
  workshopList.value.splice(idx + 1, 0, { id: generateId(), name: '' })
}
const removeWorkshopRow = (idx: number) => {
  if (workshopList.value.length > 1) workshopList.value.splice(idx, 1)
}

const editPositionDialogVisible = ref(false)
const editingPositionData = ref<any>(null)
const editingPositionName = ref('')

// 检查指定岗位是否有非稳定接触类型
const hasUnstableContactType = (position: PositionBlock) => {
  return position.workPosition === '非稳定'
}

// 计算采样时长的计算属性
const calculateSampleDuration = (row: ExpandedTableItem) => {
  if (!row.hazard?.sampling) return 0

  const timeType = row.hazard.sampling.timeType
  const contactTime = parseFloat(row.contactTime || '0')

  // 如果用户手动修改过采样时长，返回当前值
  if (row.hazard.sampling.isCustomTime) {
    return row.hazard.sampling.sampleDuration || 0
  }

  // 根据采样时间类型自动计算
  let autoDuration = 0
  if (timeType === 'short') {
    // 短时间：15分钟
    autoDuration = 15
  } else if (timeType === 'long') {
    // 长时间：接触时间 × 0.25，最低60分钟
    autoDuration = Math.max(contactTime * 0.25 * 60, 60)
  } else {
    autoDuration = row.hazard.sampling.sampleDuration || '—'
  }

  // 将自动计算结果同步回数据（仅在未自定义时）
  const prev = row.hazard.sampling.sampleDuration || 0
  if (autoDuration !== prev) {
    row.hazard.sampling.sampleDuration = autoDuration
    // 触发一次保存（只在值变化时）
    setTimeout(() => {
      surveyStore.printSurveyData()
    }, 0)
  }

  return autoDuration
}

// 处理采样时长输入
const handleSampleDurationInput = (row: ExpandedTableItem, value: string) => {
  if (!row.hazard?.sampling) return

  const numValue = parseFloat(value) || 0

  // 标记为手动修改
  row.hazard.sampling.isCustomTime = true
  row.hazard.sampling.sampleDuration = numValue

  // 同步到原始数据
  const position = findPositionByRow(row)
  if (position) {
    const originalRowId = row.originalId
    const originalRow = position.tableData.find((item) => item.id === originalRowId)
    if (originalRow) {
      const hazardId = row.hazard.id
      const hazardIndex = originalRow.hazards.findIndex((h) => h.id === hazardId)
      if (hazardIndex !== -1 && originalRow.hazards[hazardIndex].sampling) {
        originalRow.hazards[hazardIndex].sampling.isCustomTime = true
        originalRow.hazards[hazardIndex].sampling.sampleDuration = numValue
      }
    }
  }

  // 保存数据
  surveyStore.printSurveyData()
}

// 添加危害从同步结果
const addHazardsFromSyncResults = async (syncResults: Array<{ post: string; cnName: string }>) => {
  console.log('收到同步结果:', syncResults)

  if (!syncResults || syncResults.length === 0) {
    ElMessage.warning('没有同步结果数据')
    return
  }

  for (const result of syncResults) {
    await addHazardByLocation(result.post, result.cnName)
  }

  ElMessage.success(`成功同步 ${syncResults.length} 个危害信息`)
}

// 根据车间/岗位/工作地点添加危害
const addHazardByLocation = async (post: string, cnName: string) => {
  console.log(`开始添加危害: 地点=${post}, 危害=${cnName}`)

  // 解析 post 格式：车间名称/岗位名称/工作地点
  const parts = post.split('/')
  if (parts.length !== 3) {
    console.error('post 格式不正确，应为：车间名称/岗位名称/工作地点')
    return
  }

  const [workshopName, positionName, workplaceName] = parts
  console.log(`解析结果: 车间=${workshopName}, 岗位=${positionName}, 工作地点=${workplaceName}`)

  // 查找对应的车间
  const workshop = tabList.value.find((tab) => tab.name === workshopName)
  if (!workshop) {
    console.error(`未找到车间: ${workshopName}`)
    return
  }

  // 查找对应的岗位
  const position = workshop.positions.find((pos) => pos.name === positionName)
  if (!position) {
    console.error(`在车间 ${workshopName} 中未找到岗位: ${positionName}`)
    return
  }
  // console.log('position.tableData',JSON.stringify(position.tableData))
  // 查找对应的工作地点行
  const workplaceRow = position.tableData.find((row) => {
    const testItemContent =
      typeof row.testItem === 'string' ? row.testItem : row.testItem?.content || ''
    console.log('testItemContent1', JSON.stringify(testItemContent))
    console.log('workplaceName1', JSON.stringify(workplaceName))
    return row.workLocation === 1 && testItemContent.includes(workplaceName)
  })
  // console.log('workplaceRow',JSON.stringify(workplaceRow))
  if (!workplaceRow) {
    console.error(`在岗位 ${positionName} 中未找到工作地点: ${workplaceName}`)
    return
  }

  try {
    // 调用 getByName 获取危害信息
    const hazardsResponse = await HazardsApi.getByName(cnName)
    console.info('获取危害信息成功:', JSON.stringify(hazardsResponse))
    const matchedHazard = hazardsResponse.data || hazardsResponse

    if (!matchedHazard) {
      console.error(`未找到危害: ${cnName}`)
      return
    }

    console.log(`找到危害信息:`, matchedHazard)

    // 检查是否已存在该危害
    const existingHazardIndex = workplaceRow.hazards?.findIndex((h) => h.cnName === cnName) ?? -1

    // 创建新的危害对象，基于返回的完整危害信息
    const newHazard = {
      id: matchedHazard.id,
      type: matchedHazard.type,
      cnName: matchedHazard.cnName,
      letter: matchedHazard.letter || '',
      contactTime: position.workHours || '8',
      workContent: '',
      laborIntensity: '',
      source: `${workplaceName.replace(/工位$/, '')}时产生${cnName}`,
      operationType: props.operationType, // 设置操作类型
      sampling: {
        sampleDays: 1,
        pointCount: 1,
        sampleCount: 1,
        contactHours: parseInt(position.workHours) || 8,
        startDay: 1,
        timeType: matchedHazard.longTime ? 'long' : 'short',
        sampleType: workplaceRow.workLocation === 1 ? 'fix' : 'personal',
        isCustomTime: false,
        sampleDuration: 0,
        flowRate: parseFloat(matchedHazard.longTimeFlow || matchedHazard.shortTimeFlow || '0'),
        strengthType: 1
      },
      contactFrequency: {
        count: 1,
        duration: 1,
        interval: 1
      },
      personalProtection: '',
      personalProtectionList: [],
      personalProtectionIds: [],
      protectiveFacilities: '',
      protectiveFacilitiesList: [],
      protectiveFacilitiesIds: [],
      fluctuationTime: '',
      remark: '',
      airCollector: matchedHazard.airCollectors || '',
      airCollectorList: matchedHazard.airCollectors ? [matchedHazard.airCollectors] : [],
      airCollectorIds: [],
      workLocation: workplaceRow.workLocation,
      testStandard: matchedHazard.testStandard || '',
      testStandardList: matchedHazard.testStandard ? [matchedHazard.testStandard] : [],
      measuringEquipment: matchedHazard.measuringEquipment || '',
      measuringEquipmentList: matchedHazard.measuringEquipment
        ? [matchedHazard.measuringEquipment]
        : [],
      storageLife: matchedHazard.storageLife || '',
      storageLifeList: matchedHazard.storageLife ? [matchedHazard.storageLife] : [],
      // 添加限值信息
      mac: matchedHazard.mac || '',
      pcTwa: matchedHazard.pcTwa || '',
      pcStel: matchedHazard.pcStel || '',
      expiratoryDust: matchedHazard.expiratoryDust || '',
      totalDust: matchedHazard.totalDust || '',
      // 添加其他必要字段
      worker: [],
      contactTiming: `${workplaceName.replace(/工位$/, '')}时`,
      isDeleted: false
    }

    // 添加危害到工作地点行
    if (!workplaceRow.hazards) {
      workplaceRow.hazards = []
    }

    if (existingHazardIndex >= 0) {
      // 如果已存在，更新现有危害（参考handleHazardUpdate的逻辑）
      console.log(`更新已存在的危害 ${cnName} 在工作地点 ${workplaceName}`)
      workplaceRow.hazards[existingHazardIndex] = {
        ...workplaceRow.hazards[existingHazardIndex],
        ...newHazard
      }
    } else {
      // 如果不存在，添加新危害
      console.log(`添加新危害 ${cnName} 到工作地点 ${workplaceName}`)
      workplaceRow.hazards.push(newHazard)
    }

    // 参考handleHazardUpdate的逻辑，如果当前是workLocation=1的行，需要同步到workLocation=2的行
    if (workplaceRow.workLocation === 1) {
      console.log('当前是 workLocation=1 的行，开始同步到 workLocation=2 的行')

      // 在同一个 position 中查找 workLocation=2 的行
      const targetRows = position.tableData.filter((item) => item.workLocation === 2)
      console.log('找到的 workLocation=2 的行数量:', targetRows.length)

      if (targetRows.length > 0) {
        // 创建用于workLocation=2的危害副本
        const hazardForWorker = {
          ...newHazard,
          sampling: {
            ...newHazard.sampling,
            sampleType: 'personal' // 工人采样使用personal
          },
          workLocation: 2
        }

        targetRows.forEach((targetRow) => {
          if (!targetRow.hazards) {
            targetRow.hazards = []
          }

          const existingWorkerHazardIndex = targetRow.hazards.findIndex(
            (h) =>
              String(h.id) === String(hazardForWorker.id) && h.cnName === hazardForWorker.cnName
          )

          if (existingWorkerHazardIndex >= 0) {
            // 更新已存在的工人危害
            console.log(`更新工人行中已存在的危害 ${cnName}`)
            targetRow.hazards[existingWorkerHazardIndex] = {
              ...targetRow.hazards[existingWorkerHazardIndex],
              ...hazardForWorker
            }
          } else {
            // 添加新的工人危害
            console.log(`添加新危害 ${cnName} 到工人行`)
            targetRow.hazards.push(hazardForWorker)
          }
        })
      }
    }

    console.log(`成功添加/更新危害 ${cnName} 到工作地点 ${workplaceName}`)

    // 保存数据到store（参考handleHazardUpdate的逻辑）
    // surveyStore.printSurveyData()
  } catch (error) {
    console.error('获取危害信息失败:', error)
  }
}

// 修改 onMounted
onMounted(async () => {
  try {
    // 1. 从 store 加载数据
    const savedData = await surveyStore.loadSurveyData()
    // console.log('加载的数据:', JSON.stringify(savedData, null, 2))

    if (savedData && Array.isArray(savedData)) {

      // ==================== 新增：恢复默认参数配置 ====================
      // 逻辑：遍历数据，找到第一个有效的岗位，将其工作时间/天数/班制读取出来作为默认值
      // 这样刷新页面后，顶部输入框会显示为项目中实际正在使用的配置，而不是初始值
      let configRestored = false
      for (const tab of savedData) {
        if (tab.positions && tab.positions.length > 0) {
          const firstPos = tab.positions[0]
          if (firstPos) {
            // 恢复 h/d (工作时间)
            if (firstPos.workHours !== undefined && firstPos.workHours !== null) {
              defaultWorkHours.value = Number(firstPos.workHours)
            }
            // 恢复 d/w (周工作天数)
            if (firstPos.workDays !== undefined && firstPos.workDays !== null) {
              defaultWorkDays.value = Number(firstPos.workDays)
            }
            // 恢复 班制
            if (firstPos.shiftSystem) {
              defaultShiftSystem.value = firstPos.shiftSystem
            }

            // 恢复 工作时段 (如果第一个岗位有自定义时段，也同步到默认设置)
            if (firstPos.workTimeSegments && firstPos.workTimeSegments.length > 0) {
              defaultWorkTimeSegments.value = JSON.parse(JSON.stringify(firstPos.workTimeSegments))
            }

            configRestored = true
            break // 找到一个就停止，以第一个为准
          }
        }
        if (configRestored) break
      }
      // =============================================================

      // 2. 加载完数据后，先同步所有岗位的劳动者行接触时间
      console.log('[数据加载] 开始同步所有岗位的劳动者行接触时间')
      let needSave = false
      savedData.forEach((workshop: any) => {
        if (workshop.positions && Array.isArray(workshop.positions)) {
          workshop.positions.forEach((position: any) => {
            if (position.tableData && Array.isArray(position.tableData)) {
              // 检查是否有劳动者行需要更新 (workLocation === 2)
              const laborerRows = position.tableData.filter((row: any) => row.workLocation === 2)
              if (
                laborerRows.length > 0 &&
                laborerRows.some((row: any) => row.hazards && row.hazards.length > 0)
              ) {
                console.log(`[数据加载] 同步岗位 "${position.name}" 的接触时间`)
                syncContactTimeToLaborers(position)
                needSave = true
              }
            }
          })
        }
      })
      console.log('[数据加载] 所有岗位的接触时间同步完成')

      // 3. 将同步后的数据更新到 store
      surveyStore.updateTabList(savedData)
      if (savedData.length > 0) {
        surveyStore.updateActiveTab(savedData[0].id)
      }

      // 4. 如果有同步操作(接触时间变化)，保存数据到数据库
      if (needSave) {
        console.log('[数据加载] 检测到接触时间有更新，保存数据到数据库')
        // 使用 nextTick 确保 DOM 更新后再保存
        nextTick(() => {
          surveyStore.printSurveyData()
        })
      }
    } else {
      // 如果没有数据，初始化空数据
      surveyStore.updateTabList([])
      surveyStore.updateActiveTab('')
    }

    // 添加点击其他区域保存表格编辑状态的监听
    document.addEventListener('mousedown', handleTableClick)
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败，请刷新页面重试')
    // 确保即使出错也初始化为空数据
    surveyStore.updateTabList([])
    surveyStore.updateActiveTab('')
  }
})

// 暴露方法给父组件
defineExpose({
  addHazardsFromSyncResults
})
</script>

<style lang="scss" scoped>

.hazard-cell-content {
  display: flex;
  justify-content: center; /* This centers the hazard name */
  align-items: center;
  position: relative;      /* Establishes a positioning context for the status text */
  width: 100%;             /* Ensures the container spans the full width available */
}

.sampling-status {
  position: absolute;      /* Positions the element relative to its parent (.hazard-cell-content) */
  right: 0;                /* Aligns the element to the far right */
  color: #f56c6c;
  white-space: nowrap;     /* Prevents "(不采样)" from wrapping on smaller widths */
}

.workshop-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 1px;

  .workshop-input {
    flex: 1;
    min-width: 0;
  }

  .workshop-btn {
    margin-left: 4px;

    &.add {
      color: #409eff;
      border-color: #c6e2ff;
      background: #ecf5ff;
    }

    &.del {
      color: #f56c6c;
      border-color: #fde2e2;
      background: #fef0f0;
    }

    &:hover {
      filter: brightness(1.1);
    }
  }
}

.job-survey {
  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 200px;
    background-color: transparent;
  }

  :deep(.el-table) {
    // 修改表格行高以适应更多内容
    .el-table__row {
      height: auto; // 允许自动调整高度
      min-height: 100px; // 设置最小高度
    }

    // 检测项目列的样式
    .test-item-cell {
      padding: 8px;
      display: flex;
      flex-direction: column;
      gap: 8px;

      .main-item {
        font-weight: bold;
        font-size: 14px;
        color: var(--el-text-color-primary);
      }

      .sub-items {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .sub-item {
          display: flex;
          font-size: 12px;
          line-height: 1.4;
          align-items: center; // 添加垂直居中对齐

          .label {
            color: var(--el-text-color-secondary);
            width: 55px; // 减小标签宽度
            flex-shrink: 0;
            margin-right: 4px; // 减小右侧间距
          }

          .value-wrapper {
            flex: 1;
            display: flex;
            align-items: center;

            > span {
              width: 100%;
              height: 24px;
              line-height: 24px;
              text-align: center;
              cursor: text;
            }

            .edit-input {
              width: 100%;

              :deep(.el-input__wrapper) {
                padding: 0 8px;
                height: 24px;
                box-shadow: none;

                .el-input__inner {
                  height: 24px;
                  line-height: 24px;
                  font-size: 12px;
                  text-align: center;
                }
              }
            }
          }
        }
      }
    }

    // 危害名称列样式
    .el-tag {
      margin: 2px 0;
    }

    // 修改数字输入框样式
    .full-width-number-input {
      width: 100% !important; // 使用100%宽度填充单元格

      :deep(.el-input__wrapper) {
        padding: 0 24px 0 8px; // 右侧留出控制按钮的空间
        height: 24px;

        .el-input__inner {
          height: 24px;
          line-height: 24px;
          font-size: 12px;
          text-align: center; // 数字居中显示
        }
      }

      :deep(.el-input-number__decrease),
      :deep(.el-input-number__increase) {
        height: 11px;
        width: 20px;
        line-height: 11px;
        font-size: 10px;
        top: 1px; // 微调按钮位置
        right: 1px;
      }

      :deep(.el-input-number__decrease) {
        bottom: 1px;
        top: auto;
      }
    }

    // 添加可编辑单元格的样式
    .edit-input {
      width: 100%;

      :deep(.el-input__wrapper) {
        padding: 0 8px;
        height: 24px;
        box-shadow: none;

        .el-input__inner {
          height: 24px;
          line-height: 24px;
          font-size: 12px;
          text-align: center;
        }
      }
    }

    // 非编辑状态的单元格样式
    .el-table__cell {
      .cell {
        text-align: center;

        > span {
          display: block;
          width: 100%;
          height: 24px;
          line-height: 24px;
          cursor: text;
        }
      }
    }

    .workshop-prefix {
      color: var(--el-color-primary);
      font-weight: bold;
      background-color: var(--el-color-primary-light-9);
      padding: 2px 6px;
      border-radius: 4px;
      margin-right: 4px;
      font-size: 12px;
      display: inline-block;
      line-height: 1.4;
    }

    .main-item {
      // ... 保持不变

      :deep(.workshop-prefix) {
        color: var(--el-color-primary);
        font-weight: bold;
        background-color: var(--el-color-primary-light-9);
        padding: 2px 6px;
        border-radius: 4px;
        margin-right: 4px;
        font-size: 12px;
        display: inline-block;
        line-height: 1.4;
      }
    }
  }

  // 修改 tag-container 样式
  .tag-container {
    width: 100%;
    min-height: 32px;
    padding: 4px 4px 4px 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    align-items: center;

    .el-tag {
      margin: 2px;
      white-space: nowrap;
    }
  }

  .flex.items-center {
    display: flex;
    align-items: center;
    height: 100%; // 使用100%高度
    width: 100%; // 确保宽度100%
  }

  .select-btn {
    min-width: 32px;
    height: 24px;
    padding: 0 8px;
    border-radius: 12px;
    font-size: 12px;
    background-color: var(--el-color-primary-light-9);
    border: 1px solid var(--el-color-primary-light-5);
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: auto 0; // 添加这个以确保垂直居中
    flex-shrink: 0; // 防止按钮被压缩

    &:hover {
      background-color: var(--el-color-primary-light-8);
      border-color: var(--el-color-primary);
    }

    &:active {
      background-color: var(--el-color-primary-light-7);
    }
  }

  .tab-label {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .base-info {
    background-color: var(--el-fill-color-blank);
    padding: 16px 20px;
    border-radius: 4px;
    border: 1px solid var(--el-border-color-lighter);

    .info-item {
      display: flex;
      align-items: center;
      height: 32px;
      margin-bottom: 8px; // 添加底部间距

      .label {
        color: var(--el-text-color-regular);
        width: 84px;
        text-align: right;
        padding-right: 12px;
        font-size: 14px;
        flex-shrink: 0; // 防止标签收缩
      }

      // 工作时段显示区域对齐
      .work-time-display {
        flex: 1;
        min-width: 0; // 允许收缩
      }

      :deep(.el-input-number),
      :deep(.el-select),
      :deep(.el-time-picker) {
        .el-input__wrapper {
          padding: 0 8px;
          height: 32px;
          line-height: 32px;
        }

        .el-input__inner {
          font-size: 14px;
        }
      }
    }

    .el-row {
      &:not(:last-child) {
        margin-bottom: 16px;
      }
    }
  }

  .add-position-btn {
    padding: 8px 16px;
    font-size: 14px;
    height: 32px;
    display: flex;
    align-items: center;

    :deep(.el-icon) {
      font-size: 14px;
    }
  }

  .position-block {
    background-color: #fff;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 24px;
    border: 1px solid var(--el-border-color-light);

    .position-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid var(--el-border-color-lighter);

      .position-title-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;

        .left-group {
          display: flex;
          align-items: center;
          gap: 15px;
        }

        .position-title {
          margin: 0;
          display: flex;
          align-items: center;
          gap: 8px;
          line-height: 1.2;

          .position-name {
            font-size: 18px;
            font-weight: 600;
            color: var(--el-text-color-primary);
          }

          .workshop-suffix {
            font-size: 12px;
            color: red;
            padding: 2px 8px;
            border-radius: 12px;
          }
        }

        .delete-icon {
          cursor: pointer;
          font-size: 16px;
          color: var(--el-text-color-regular);
          margin-left: 8px;

          &:hover {
            color: var(--el-color-danger);
          }
        }

        .add-personal-sample-btn {
          margin-left: 0;
        }
      }
    }

    .base-info {
      background-color: var(--el-fill-color-blank);
      padding: 16px 20px;
      border-radius: 4px;
      border: 1px solid var(--el-border-color-lighter);
    }

    & + .position-block {
      margin-top: 24px;
    }
  }

  /* 列显示开关：通过为表格添加 hide 类来隐藏对应列（th/td） */
  :deep(.tab-container.hide-col-test-standard) th.col-test-standard,
  :deep(.tab-container.hide-col-test-standard) td.col-test-standard {
    display: none;
  }
  :deep(.tab-container.hide-col-air-collector) th.col-air-collector,
  :deep(.tab-container.hide-col-air-collector) td.col-air-collector {
    display: none;
  }
  :deep(.tab-container.hide-col-measuring-equipment) th.col-measuring-equipment,
  :deep(.tab-container.hide-col-measuring-equipment) td.col-measuring-equipment {
    display: none;
  }
  :deep(.tab-container.hide-col-storage-life) th.col-storage-life,
  :deep(.tab-container.hide-col-storage-life) td.col-storage-life {
    display: none;
  }
  :deep(.tab-container.hide-col-flow-rate) th.col-flow-rate,
  :deep(.tab-container.hide-col-flow-rate) td.col-flow-rate {
    display: none;
  }

  // 添加危害标签样式
  .el-tag {
    &.hazard-type-1 {
      color: #409eff;
      background-color: #ecf5ff;
      border-color: #d9ecff;
    }

    &.hazard-type-2 {
      color: #67c23a;
      background-color: #f0f9eb;
      border-color: #e1f3d8;
    }

    &.hazard-type-3 {
      color: #e6a23c;
      background-color: #fdf6ec;
      border-color: #faecd8;
    }

    &.hazard-type-4 {
      color: #f56c6c;
      background-color: #fef0f0;
      border-color: #fde2e2;
    }

    &.hazard-type-5 {
      color: #909399;
      background-color: #f4f4f5;
      border-color: #e9e9eb;
    }
  }

  // 修改防护单元格样式
  .protection-cell {
    display: flex;
    width: 100%;
    min-height: 32px;
  }

  // 标签容器包装器
  .tag-wrapper {
    flex: 1;
    overflow: hidden;
    padding: 4px;
  }

  // 按钮包装器
  .btn-wrapper {
    width: 32px;
    padding: 4px;
    flex-shrink: 0;
  }

  // 标签容器样式
  .tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;

    .el-tag {
      margin: 2px;
      white-space: nowrap;
    }
  }

  // 选择按钮样式
  .select-btn {
    width: 24px;
    height: 24px;
    padding: 0;
    border-radius: 4px;
    font-size: 12px;
    background-color: var(--el-color-primary-light-9);
    border: 1px solid var(--el-color-primary-light-5);
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background-color: var(--el-color-primary-light-8);
      border-color: var(--el-color-primary);
    }

    &:active {
      background-color: var(--el-color-primary-light-7);
    }
  }

  // 工作时段按钮样式（与输入框保持一致）
  .work-time-button {
    cursor: pointer;
    padding: 4px 8px;
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    background: var(--el-fill-color-blank);
    color: var(--el-text-color-regular);
    font-size: 12px;
    text-align: center;
    min-width: 80px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
    }

    &:active {
      background: var(--el-color-primary-light-9);
    }
  }

  // 工作时段显示样式
  .work-time-display {
    cursor: pointer;
    padding: 4px 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 13px;
    transition: all 0.3s ease;
    min-height: 32px;
    display: flex;
    align-items: center;

    &:hover {
      background: #e6f3ff;
      border-color: #409eff;
      color: #409eff;
    }

    &:active {
      background: #cce8ff;
    }
  }

  // 工作时段弹窗样式
  .work-time-dialog {
    .shift-system-section {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 24px;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 6px;

      .section-label {
        font-weight: 600;
        color: #495057;
        min-width: 60px;
      }

      .shift-info {
        color: #6c757d;
        font-size: 13px;
        margin-left: 16px;
      }
    }

    .time-segments-section {
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .section-label {
          font-weight: 600;
          color: #495057;
        }
      }

      .segments-list {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #e9ecef;
        border-radius: 6px;
        padding: 8px;

        .segment-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 12px 8px;
          border-bottom: 1px solid #f1f3f5;

          &:last-child {
            border-bottom: none;
          }

          .segment-index {
            min-width: 60px;
            font-size: 13px;
            color: #6c757d;
          }

          .time-separator {
            color: #6c757d;
            margin: 0 4px;
          }

          .duration-display {
            min-width: 80px;
            font-size: 13px;
            color: #28a745;
            font-weight: 500;
          }
        }
      }

      .total-duration-section {
        margin-top: 16px;
        padding: 12px;
        background: #f8f9fa;
        border-radius: 6px;

        .total-info {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          font-weight: 500;

          .target-duration {
            color: #6c757d;
          }
        }

        .duration-warning {
          margin-top: 8px;
          color: #dc3545;
          font-size: 13px;
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }

  // 添加采样方案弹窗样式
  .sampling-plan-dialog {
    .hazard-list {
      max-height: 60vh;
      overflow-y: auto;
      padding: 8px;
    }

    .hazard-item {
      border: 1px solid var(--el-border-color-lighter);
      border-radius: 4px;
      margin-bottom: 8px;
      background-color: var(--el-fill-color-blank);

      .hazard-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        border-bottom: 1px solid var(--el-border-color-lighter);
        background-color: var(--el-fill-color-light);
      }

      .hazard-content {
        padding: 12px;
      }
    }

    .sampling-form {
      :deep(.el-form-item) {
        margin-bottom: 0;
      }
    }

    .sampling-row {
      display: flex;
      align-items: center;

      &.radio-row {
        margin-top: 12px;
      }
    }

    .hazard-tag-col {
      display: flex;
      align-items: center;

      .el-tag {
        white-space: nowrap;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .compact-form-item {
      :deep(.el-form-item__label) {
        font-size: 13px;
        padding-right: 8px;
        line-height: 32px;
      }

      :deep(.el-form-item__content) {
        line-height: 32px;
      }

      :deep(.el-input-number) {
        width: 100%;

        .el-input-number__decrease,
        .el-input-number__increase {
          position: absolute;
          z-index: 1;
          top: 1px;
          width: 20px;
          height: calc(100% - 2px);
          background: var(--el-fill-color-light);
          border: none;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .el-input-number__decrease {
          left: 1px;
          border-radius: 4px 0 0 4px;
          border-right: 1px solid var(--el-border-color);
        }

        .el-input-number__increase {
          right: 1px;
          border-radius: 0 4px 4px 0;
          border-left: 1px solid var(--el-border-color);
        }

        .el-input__wrapper {
          padding: 0 24px;
        }

        .el-input__inner {
          text-align: center;
        }
      }
    }
  }
}

/* 仅识别徽标样式，与 hazards 组件保持一致 */
:deep(.el-tag) {
  position: relative;
  padding-right: 20px;
}
:deep(.el-tag) .reco-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: var(--el-color-danger);
  color: #fff;
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 8px;
  transform: scale(0.8);
  white-space: nowrap;
}

.head-container {
  display: flex;
  justify-content: space-between;
  align-self: flex-start; // 添加这一行
  align-items: center;
  margin-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;

  .leftadd {
    display: flex;
    align-items: center;
  }

  .right-defaults {
    display: flex;
    align-items: center;

    .defaults-container {
      display: flex;
      align-items: center;
      gap: 16px;

      background: #f8f9fa;
      border: 1px solid #e9ecef;

      .defaults-title {
        font-weight: 600;
        color: #495057;
      }

      .default-item {
        display: flex;
        align-items: center;
        gap: 4px;

        .item-label {
          font-size: 12px;
          white-space: nowrap;
        }

        .unit {
          font-size: 12px;
        }

        &.work-time-section {
          display: flex;
          align-items: center;
          gap: 2px;

          .time-separator {
            margin: 0 2px;
            font-size: 12px;
          }
        }
      }
    }
  }

  .rightinfo {
    display: flex;
    align-items: center; // 添加垂直居中对齐
    gap: 2px; // 添加间距
    padding: 8px 16px; // 添加内边距
    background-color: var(--el-fill-color-light); // 修改为 Element Plus 的浅色背景

    span {
      font-size: 13px;
      white-space: nowrap; // 防止文字换行
    }

    .flex {
      display: flex;
      align-items: center;
    }
  }
}

// 添加新增岗位弹窗样式
.position-type-dialog {
  // 基础信息区域
  .base-info-config {
    background: var(--el-fill-color-blank); // 使用 Element Plus 的背景色变量
    border-radius: 4px;
    padding: 20px;

    // 标题样式
    .section-title {
      font-size: 14px;
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 20px;
      position: relative;
      padding-left: 10px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 14px;
        background: var(--el-color-primary);
        border-radius: 2px;
      }
    }

    // 表单样式
    .base-form {
      .el-form-item {
        margin-bottom: 18px;

        &:last-child {
          margin-bottom: 0;
        }

        // 表单项标签
        :deep(.el-form-item__label) {
          color: var(--el-text-color-regular);
          font-weight: normal;
        }
      }

      // 岗位名称输入框
      .base-input {
        width: 300px;
      }

      // 单选按钮组
      :deep(.el-radio-group) {
        display: flex;
        gap: 24px;

        .el-radio {
          margin: 0;

          .el-radio__label {
            color: var(--el-text-color-regular);
            font-size: 14px;
          }

          &.is-checked {
            .el-radio__label {
              color: var(--el-color-primary);
            }
          }
        }
      }
    }
  }

  // 流动岗位配置区域
  .cross-workshop-config {
    margin-top: 16px;
    padding: 20px;
    background: var(--el-fill-color-blank); // 使用相同的背景色
    border-radius: 4px;

    .section-title {
      font-size: 14px;
      margin-bottom: 12px;
      color: var(--el-text-color-regular);
    }

    // 操作工位列表
    .flow-positions-list {
      .flow-position-item {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        .workshop-select {
          width: 160px;
        }

        .work-info-input {
          flex: 1;
        }

        .position-actions {
          display: flex;
          gap: 8px;
          align-items: center;
        }

        .add-position-btn,
        .delete-position-btn {
          padding: 8px;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;

          .el-icon {
            font-size: 16px;
          }
        }

        .add-position-btn {
          color: var(--el-color-primary);

          &:hover {
            background: var(--el-color-primary-light-9);
          }
        }

        .delete-position-btn {
          color: var(--el-color-danger);

          &:hover {
            background: var(--el-color-danger-light-9);
          }
        }
      }
    }
  }
}

// 弹窗整体样式优化
:deep(.el-dialog) {
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  background: var(--el-bg-color); // 设置弹窗整体背景色

  .el-dialog__header {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .el-dialog__body {
    padding: 20px;
    background: var(--el-bg-color-page); // 设置内容区域背景色
  }

  .el-dialog__footer {
    margin: 0;
    padding: 16px 20px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

.base-info-config {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 20px;

  // 标题样式
  .section-title {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    margin-bottom: 20px;
    position: relative;
    padding-left: 10px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 3px;
      height: 14px;
      background: var(--el-color-primary);
      border-radius: 2px;
    }
  }

  // 表单样式
  .base-form {
    .el-form-item {
      margin-bottom: 18px;

      &:last-child {
        margin-bottom: 0;
      }

      // 表单项标签
      :deep(.el-form-item__label) {
        color: var(--el-text-color-regular);
        font-weight: normal;
      }
    }

    // 岗位名称输入框
    .base-input {
      width: 300px;
    }

    // 单选按钮组
    :deep(.el-radio-group) {
      display: flex;
      gap: 24px;

      .el-radio {
        margin: 0;

        .el-radio__label {
          color: var(--el-text-color-regular);
          font-size: 14px;
        }

        &.is-checked {
          .el-radio__label {
            color: var(--el-color-primary);
          }
        }
      }
    }
  }
}

.workshop-dialog {
  .form-item {
    margin-bottom: 20px;

    label {
      display: block;
      margin-bottom: 5px;
    }

    .el-input {
      width: 100%;
    }
  }
}

/* 可编辑单元格样式 */
.editable-cell {
  padding: 5px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  background-color: var(--el-fill-color-blank); // 添加默认背景色
}

.editable-cell:hover {
  background-color: var(--el-fill-color-light);
}

:deep(.el-input__wrapper) {
  box-shadow: none;
  background-color: var(--el-fill-color-blank); // 添加输入框背景色
}

:deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
  background-color: var(--el-fill-color-blank); // 保持聚焦时的背景色
}

// 添加选择器样式
:deep(.el-select__wrapper) {
  background-color: var(--el-fill-color-blank);
}

/* 调整表格内输入框样式 */
:deep(.el-table) {
  .el-input__wrapper {
    border-radius: 0;
    /* 尝试调整垂直对齐和高度 */
    border: none;
    box-shadow: none !important;
  }
}

/* 调整表格内容居中对齐 */
:deep(.el-table .cell) {
  text-align: center;
  padding: 0px 2px !important; /* 调整单元格内边距，左右再小一点 */
}

/* 调整操作列按钮间距 */
:deep(.el-table .cell .el-button + .el-button) {
  margin-left: 8px;
}

.job-survey {
  :deep(.el-input__wrapper) {
    background-color: var(--el-fill-color-blank) !important;
    box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
  }

  :deep(.el-dialog),
  :deep(.el-popover) {
    .el-input__wrapper {
      background-color: var(--el-fill-color-blank) !important;
      box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
    }
  }

  /* 表格内输入框样式 */
  :deep(.el-table) {
    .el-input__wrapper {
      padding: 0 8px;
      background-color: var(--el-fill-color-blank) !important;
      box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
    }
  }

  /* 表格内容居中对齐 */
  :deep(.el-table .cell) {
    text-align: center;
  }

  /* 操作列按钮间距 */
  :deep(.el-table .cell .el-button + .el-button) {
    margin-left: 8px;
  }
}

/* 其他现有样式保持不变 */

:deep(.el-select) {
  .el-input__suffix {
    display: none !important; // 隐藏所有下拉按钮
  }
}

// 如果上面的样式不生效，可以尝试更强的选择器
:deep(.el-input__suffix-inner) {
  display: none !important;
}

// 确保下拉框内容居中对齐
:deep(.el-select .el-input__inner) {
  text-align: center;
}

// 添加更强的选择器来隐藏下拉箭头
:deep(.el-select) {
  .el-input {
    .el-input__suffix {
      display: none !important;
    }

    .el-input__suffix-inner {
      display: none !important;
    }
  }
}

// 针对表格内的下拉选择器
:deep(.el-table) {
  .el-select {
    .el-input__suffix,
    .el-input__suffix-inner {
      display: none !important;
    }
  }
}

// 确保下拉框内容居中对齐
:deep(.el-select .el-input__inner) {
  text-align: center !important;
  padding-right: 8px !important; // 减少右侧padding
}

// 移除所有下拉图标
:deep(.el-select__caret) {
  display: none !important;
}

.job-survey {
  // 基础信息区域的输入框样式
  .base-info {
    :deep(.el-input__wrapper) {
      background-color: var(--el-fill-color-blank) !important;
      box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
      border-radius: 4px;
      padding: 1px 11px;
    }
  }

  // 表格区域的输入框样式
  :deep(.el-table) {
    .el-input__wrapper {
      padding: 0 2px;
      background-color: var(--el-bg-color) !important;
      box-shadow: none !important;
      border-radius: 0;
      min-height: 24px;
      line-height: 24px;
    }
  }
}

.testitem-action-btns {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap; /* 允许元素换行 */
}

/* 岗位管理弹窗样式 */
.position-management-dialog-wrapper {
  :deep(.el-dialog) {
    margin: 5vh auto;
  }

  :deep(.el-dialog__body) {
    padding: 16px;
    background-color: #f5f7fa;
    max-height: 80vh;
    overflow-y: auto;
  }

  .edit-mode-tip {
    margin-bottom: 16px;
  }

  .usage-tip {
    margin-bottom: 16px;
  }

  .form-header {
    margin-bottom: 5px;
    text-align: left;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      flex: 1;
    }

    .header-right {
      display: flex;
      gap: 8px;
    }
  }

  .position-form-container {
    .position-form {
      background: white;
      padding: 5px;
      margin-bottom: 16px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      cursor: pointer;
      position: relative;

      &:hover {
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        transform: translateY(-1px);
      }

      &.editing-highlight {
        border: 2px solid #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
        background: #ecf5ff;

        .position-form-grid {
          background: #ecf5ff !important;
        }
      }

      .position-form-actions {
        position: absolute;
        top: 6px;
        right: 6px;
        z-index: 2;

        .delete-position-btn {
          color: var(--el-color-danger);
        }

        .delete-position-btn:hover {
          background: var(--el-color-danger-light-9);
        }
      }

      .position-form-grid {
        :deep(.el-form-item) {
          margin-bottom: 0 !important;
        }

        .form-row {
          margin-bottom: 2px !important;

          &:last-child {
            margin-bottom: 0 !important;
          }
        }
      }
    }
  }

  .position-workplace-table {
    margin-top: 10px;

    .workplace-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 5px;

      .workplace-header-left {
        display: flex;
        align-items: center;
      }

      .workplace-header-right {
        .expand-btn {
          font-size: 12px;
          padding: 4px 8px;

          .el-icon {
            margin-right: 4px;
          }
        }
      }

      .workplace-title {
        font-weight: 500;
        color: #303133;
        font-size: 14px;
      }

      .fixed-position-tip {
        color: #909399;
        font-size: 12px;
        margin-left: 10px;
        line-height: 32px;
      }
    }

    .workplace-table-container {
      transition: all 0.3s ease;
    }

    .workplace-table {
      :deep(.el-table__header) {
        background-color: #fafafa;
      }

      :deep(.el-table th) {
        background-color: #fafafa;
        font-weight: 500;
      }
    }
  }
}

.position-form {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;

  &:last-child {
    margin-bottom: 0;
  }

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border-color: #409eff;
  }
}

.error-text {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  position: absolute;
  white-space: nowrap;
}

/* 新增车间弹窗内的样式优化 */
/* 默认参数区域样式优化 */
.dialog-defaults-wrapper {
  background-color: #f8f9fb;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 20px;

  .defaults-header {
    margin-bottom: 16px;
    display: flex;
    align-items: baseline;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;

    .title {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }
    .subtitle {
      font-size: 12px;
      color: #909399;
      margin-left: 6px;
    }
  }

  .defaults-content {
    /* 核心修改：使用 Grid 布局，强制一行两列 */
    .defaults-grid {
      display: grid;
      grid-template-columns: 1fr 1fr; /* 1:1 等分两列 */
      column-gap: 30px; /* 列间距 */
      row-gap: 18px;    /* 行间距 */
    }

    .default-item {
      display: flex;
      align-items: center;
      width: 100%;

      /* 固定标签宽度，保证上下对齐 */
      .item-label {
        font-size: 13px;
        color: #606266;
        width: 70px;       /* 固定宽度 */
        text-align: right; /* 文字右对齐 */
        margin-right: 10px;
        white-space: nowrap;
        flex-shrink: 0;
      }

      /* 让组件占满剩余空间 */
      .el-input-number,
      .el-select,
      .time-setting-btn {
        flex: 1;
        width: 100%; /* 强制宽度 */
      }

      .time-setting-btn {
        justify-content: flex-start;
        padding-left: 10px;
      }
    }
  }
}

.workshop-form {
  padding: 0 10px;
}


/* ================= 新增车间弹窗美化样式 ================= */

/* 弹窗主体 */
:deep(.workshop-add-dialog) {
  border-radius: 8px;
  overflow: hidden;

  .el-dialog__header {
    margin-right: 0;
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 24px;
  }

  .el-dialog__body {
    padding: 20px 24px;
  }

  .el-dialog__footer {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
}

/* 默认参数区域 */
.dialog-defaults-wrapper {
  background-color: #f8f9fb;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 20px;

  .defaults-header {
    margin-bottom: 12px;
    display: flex;
    align-items: baseline;

    .title {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }
    .subtitle {
      font-size: 12px;
      color: #909399;
      margin-left: 6px;
    }
  }

  .defaults-content {
    .defaults-row {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 24px; /* 参数之间的间距 */

      &.mt-3 {
        margin-top: 12px;
      }
    }

    .default-item {
      display: flex;
      align-items: center;

      .item-label {
        font-size: 13px;
        color: #606266;
        margin-right: 8px;
        white-space: nowrap;
      }

      .time-setting-btn {
        padding: 8px 16px;
        font-weight: normal;
      }
    }
  }
}

/* 车间列表区域 */
.workshop-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  padding: 0 4px;
}

.workshop-list-scroll {
  max-height: 550px; /* 限制高度 */
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 6px; /* 给滚动条留出空间 */

  /* 滚动条样式 */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background: #e4e7ed;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-track {
    background: transparent;
  }
}

.workshop-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  background-color: #fff;

  .row-index {
    width: 30px;
    font-size: 13px;
    color: #909399;
    text-align: center;
    font-family: monospace;
    margin-right: 8px;
  }

  .workshop-input {
    flex: 1;
  }

  .row-actions {
    display: flex;
    align-items: center;
    margin-left: 10px;
    gap: 6px;
    width: 80px; /* 固定宽度防止抖动 */
  }
}

/* 底部栏 */
.dialog-footer-custom {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .footer-left {
    .summary {
      font-size: 13px;
      color: #606266;
      b {
        color: var(--el-color-primary);
      }
    }
  }
}

/* 列表动画 */
.list-transition-enter-active,
.list-transition-leave-active {
  transition: all 0.3s ease;
}
.list-transition-enter-from,
.list-transition-leave-to {
  opacity: 0;
  transform: translateX(-10px);
}
</style>

<style scoped>
/* 组件局部样式 */
.job-survey {
  :deep(.el-input__wrapper) {
    /*background-color: var(--el-fill-color-blank) !important;*/
    /*box-shadow: 0 0 0 1px var(--el-border-color) inset !important;*/
    background-color: var(--el-bg-color) !important;
    /* 移除表单中 el-input 的边框 */
    box-shadow: none !important;
    border-radius: 4px;
    padding: 1px 11px;
  }

  /* 去掉表格中的 */

  :deep(.el-table) {
    .el-input__wrapper {
      padding: 0 2px; /* 进一步减小表格内输入框的左右内边距 */
      background-color: var(--el-bg-color) !important;
      box-shadow: none !important;
      border-radius: 0;
      /* 尝试调整垂直对齐和高度 */
      min-height: 24px; /* 设置最小高度，与子项高度一致 */
      line-height: 24px; /* 设置行高 */
    }
  }

  :deep(.el-table .el-table__body td) {
    padding: 0px 0; /* 将这里的 6px 调整为你需要的大小 */
  }
}

.column-settings {
  display: flex;
  flex-direction: column;
  gap: 8px; /* 增加复选框之间的间距 */
}

.popover-footer {
  display: flex;
  justify-content: flex-end; /* 按钮靠右对齐 */
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px solid var(--el-border-color-lighter); /* 添加分割线 */
  gap: 8px;
}
</style>


